fork download
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. void format(FILE *f, const char *fmt, const void **s)
  6. {
  7. const char *p = strchr(fmt, '%');
  8.  
  9. while (p) {
  10. int len = p - fmt;
  11.  
  12. fprintf(f, "%.*s", len, fmt);
  13. p++;
  14.  
  15. switch (*p++) {
  16. case 'd': if (*s) fprintf(f, "%d", *(const int *) *s++); break;
  17. case 'f': if (*s) fprintf(f, "%f", *(const double *) *s++); break;
  18. case 's': if (*s) fprintf(f, "%s", (const char *) *s++); break;
  19. default: fprintf(f, "{Illegal fmt char}");
  20. }
  21.  
  22. fmt = p;
  23. p = strchr(fmt, '%');
  24. }
  25.  
  26. fputs(fmt, f);
  27. fputs("\n", f);
  28. }
  29.  
  30. #define M_HEAD(a, ...) a
  31. #define M_TAIL(a, ...) __VA_ARGS__
  32. #define format(...) format(stdout, M_HEAD(__VA_ARGS__), \
  33.   (const void *[]){M_TAIL(__VA_ARGS__, NULL)})
  34.  
  35. int main(void)
  36. {
  37. const char *fn = "example.txt";
  38.  
  39. double pi = 22.0 / 7.0;
  40. int n = 56;
  41. int code = -29;
  42.  
  43. format("%s, %s, %s, %s.", "Alpha", "Bravo", "Charlie", "Delta");
  44. format("Couldn't open \"%s\": error code %d.", fn, &code);
  45. format("Today's number is %d.", &n);
  46. format("And a super approximation for pi is %f.", &pi);
  47. format("Look Ma, no arguments!");
  48.  
  49. return 0;
  50. }
  51.  
Success #stdin #stdout 0s 9432KB
stdin
Standard input is empty
stdout
Alpha, Bravo, Charlie, Delta.
Couldn't open "example.txt": error code -29.
Today's number is 56.
And a super approximation for pi is 3.142857.
Look Ma, no arguments!