Skip to content

Instantly share code, notes, and snippets.

@wd5gnr
Created October 3, 2023 16:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wd5gnr/926429d015e5125d7fd0ba7dd9904799 to your computer and use it in GitHub Desktop.
Save wd5gnr/926429d015e5125d7fd0ba7dd9904799 to your computer and use it in GitHub Desktop.
Example of custom printf specifier
#include <stdio.h>
#include <stdlib.h>
#include <printf.h>
static int print_coin (FILE *stream,
const struct printf_info *info,
const void *const *args)
{
int headstails;
char *buffer;
int len;
/* figure out our string */
headstails = *((const int *) (args[0]));
if (info->width!=1)
{
buffer=(headstails&1)?"HEADS":"TAILS";
}
else
{
buffer=(headstails&1)?"H":"T";
}
/* Pad to the minimum field width and print to the stream. */
len = fprintf (stream, "%*s",
(info->left ? -info->width : info->width),
buffer);
return len;
}
static int print_coin_arginfo (const struct printf_info *info, size_t n,
int argtypes[],int size[])
{
/* We always take exactly one argument and this is the coin flip */
if (n > 0)
argtypes[0] = PA_INT;
return 1;
}
// This is the only externally reachable function
void register_coin_printf(void)
{
register_printf_specifier('H',print_coin,print_coin_arginfo);
}
#if 1 // remove for library use
int main (int argc, char *argv[])
{
char output[64];
/* Register the print function for Coin Flips */
register_coin_printf();
printf("%H %H %H %H\n",1,2,3,4);
printf("%1H %1H\n",0,1);
printf("%20H %20H\n",100,33);
printf("%20H %-20H\n",100,33);
sprintf(output,"%H",1);
printf("->%s\n",output);
return 0;
}
#endif
@wd5gnr
Copy link
Author

wd5gnr commented Oct 3, 2023

Use -Wno-format or add these pragrams:
#pragma GCC diagnostic ignored "-Wformat"
#pragma GCC diagnostic ignored "-Wformat-extra-args"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment