fork(1) download
  1. // Join items on output stream. (3.01)
  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. for (;;) {
  15. if (reverse) {
  16. last -= itemsize;
  17. putitem(last, stream);
  18. } else {
  19. putitem(first, stream);
  20. first += itemsize;
  21. }
  22. if (first == last)
  23. break;
  24. fputs(separator, stream);
  25. }
  26. }
  27. }
  28.  
  29. // Use.
  30.  
  31. void putint(const void *item, FILE *stream)
  32. {
  33. fprintf(stream, "%d", *(const int *) item);
  34. }
  35.  
  36. void print_ints(const int *a, size_t n, int end, _Bool reverse)
  37. {
  38. putchar('[');
  39. ostream_join(a, n, sizeof *a, putint, ", ", stdout, reverse);
  40. putchar(']');
  41. if (end != 0)
  42. putchar(end);
  43. }
  44.  
  45. int main(void)
  46. {
  47. int a[] = {1, 2, 3, 4};
  48. print_ints(a, sizeof a / sizeof *a, '\n', 0);
  49. print_ints(a, sizeof a / sizeof *a, '\n', 1);
  50. return 0;
  51. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
[1, 2, 3, 4]
[4, 3, 2, 1]