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