Created
October 3, 2023 16:32
-
-
Save wd5gnr/926429d015e5125d7fd0ba7dd9904799 to your computer and use it in GitHub Desktop.
Example of custom printf specifier
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use -Wno-format or add these pragrams:
#pragma GCC diagnostic ignored "-Wformat"
#pragma GCC diagnostic ignored "-Wformat-extra-args"