fork download
  1. // Join items on output stream. (3.03)
  2.  
  3. #include <stdio.h>
  4.  
  5. void ostream_join(
  6. const void *base, size_t nitems, size_t itemsize,
  7. void (*putitem)(const void *item, FILE *stream),
  8. const char *separator, FILE *stream, _Bool reverse)
  9. {
  10. const char *first = base;
  11. const char *last = first + nitems*itemsize;
  12.  
  13. if (first != last)
  14. {
  15. for (;;) {
  16. if (reverse)
  17. {
  18. last -= itemsize;
  19. putitem(last, stream);
  20. }
  21. else
  22. {
  23. putitem(first, stream);
  24. first += itemsize;
  25. }
  26. if (first == last)
  27. break;
  28. fputs(separator, stream);
  29. }
  30. }
  31. }
  32.  
  33. // Specialize.
  34.  
  35. #define DEFINE_PRINTER(name, proc, type) \
  36. void name(const type *a, size_t n, int end, _Bool reverse) \
  37. { \
  38.   putchar('['); \
  39.   ostream_join(a, n, sizeof *a, proc, ", ", stdout, reverse); \
  40.   putchar(']'); \
  41.   if (end != 0) \
  42.   putchar(end); \
  43. }
  44.  
  45. struct point {
  46. int x, y;
  47. };
  48.  
  49. static void putpoint_(const void *item, FILE *stream)
  50. {
  51. const struct point *p = item;
  52. fprintf(stream, "(%d, %d)", p->x, p->y);
  53. }
  54.  
  55. DEFINE_PRINTER(print_points, putpoint_, struct point)
  56.  
  57. int main(void)
  58. {
  59. struct point a[] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};
  60. print_points(a, sizeof a / sizeof *a, '\n', 0);
  61. print_points(a, sizeof a / sizeof *a, '\n', 1);
  62. return 0;
  63. }
Success #stdin #stdout 0s 5272KB
stdin
Standard input is empty
stdout
[(1, 2), (3, 4), (5, 6), (7, 8)]
[(7, 8), (5, 6), (3, 4), (1, 2)]