// Join items on output stream. (3.02)
#include <stdio.h>
void ostream_join(
const void *base, size_t nitems, size_t itemsize,
void (*putitem)(const void *item, FILE *stream),
const char *separator, FILE *stream, _Bool reverse)
{
const char *first = base;
const char *last = first + nitems*itemsize;
if (first != last) {
for (;;) {
if (reverse) {
last -= itemsize;
putitem(last, stream);
} else {
putitem(first, stream);
first += itemsize;
}
if (first == last)
break;
fputs(separator
, stream
); }
}
}
// Use.
static void puti_(const void *item, FILE *stream)
{
fprintf(stream
, "%d", *(const int *) item
); }
void print_ints(const int *a, size_t n, int end, _Bool reverse)
{
ostream_join(a, n, sizeof *a, puti_, ", ", stdout, reverse);
if (end != 0)
}
int main(void)
{
int a[] = {1, 2, 3, 4};
print_ints(a, sizeof a / sizeof *a, '\n', 0);
print_ints(a, sizeof a / sizeof *a, '\n', 1);
return 0;
}
Ly8gSm9pbiBpdGVtcyBvbiBvdXRwdXQgc3RyZWFtLiAoMy4wMikKCiNpbmNsdWRlIDxzdGRpby5oPgoKdm9pZCBvc3RyZWFtX2pvaW4oCiAgICBjb25zdCB2b2lkICpiYXNlLCBzaXplX3Qgbml0ZW1zLCBzaXplX3QgaXRlbXNpemUsCiAgICB2b2lkICgqcHV0aXRlbSkoY29uc3Qgdm9pZCAqaXRlbSwgRklMRSAqc3RyZWFtKSwKICAgIGNvbnN0IGNoYXIgKnNlcGFyYXRvciwgRklMRSAqc3RyZWFtLCBfQm9vbCByZXZlcnNlKQp7CiAgICBjb25zdCBjaGFyICpmaXJzdCA9IGJhc2U7CiAgICBjb25zdCBjaGFyICpsYXN0ID0gZmlyc3QgKyBuaXRlbXMqaXRlbXNpemU7CgogICAgaWYgKGZpcnN0ICE9IGxhc3QpIHsKICAgICAgICBmb3IgKDs7KSB7CiAgICAgICAgICAgIGlmIChyZXZlcnNlKSB7CiAgICAgICAgICAgICAgICBsYXN0IC09IGl0ZW1zaXplOwogICAgICAgICAgICAgICAgcHV0aXRlbShsYXN0LCBzdHJlYW0pOwogICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgICAgcHV0aXRlbShmaXJzdCwgc3RyZWFtKTsKICAgICAgICAgICAgICAgIGZpcnN0ICs9IGl0ZW1zaXplOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGlmIChmaXJzdCA9PSBsYXN0KQogICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGZwdXRzKHNlcGFyYXRvciwgc3RyZWFtKTsKICAgICAgICB9CiAgICB9Cn0KCi8vIFVzZS4KCnN0YXRpYyB2b2lkIHB1dGlfKGNvbnN0IHZvaWQgKml0ZW0sIEZJTEUgKnN0cmVhbSkKewogICAgZnByaW50ZihzdHJlYW0sICIlZCIsICooY29uc3QgaW50ICopIGl0ZW0pOwp9Cgp2b2lkIHByaW50X2ludHMoY29uc3QgaW50ICphLCBzaXplX3QgbiwgaW50IGVuZCwgX0Jvb2wgcmV2ZXJzZSkKewogICAgcHV0Y2hhcignWycpOwogICAgb3N0cmVhbV9qb2luKGEsIG4sIHNpemVvZiAqYSwgcHV0aV8sICIsICIsIHN0ZG91dCwgcmV2ZXJzZSk7CiAgICBwdXRjaGFyKCddJyk7CiAgICBpZiAoZW5kICE9IDApCiAgICAgICAgcHV0Y2hhcihlbmQpOwp9CgppbnQgbWFpbih2b2lkKQp7CiAgICBpbnQgYVtdID0gezEsIDIsIDMsIDR9OwogICAgcHJpbnRfaW50cyhhLCBzaXplb2YgYSAvIHNpemVvZiAqYSwgJ1xuJywgMCk7CiAgICBwcmludF9pbnRzKGEsIHNpemVvZiBhIC8gc2l6ZW9mICphLCAnXG4nLCAxKTsKICAgIHJldHVybiAwOwp9