I used three buffers for this: input, temp, and output:
Code:
if (setvbuf(fd, NULL, (int)_IOFBF, BUFSIZE) != 0) {
  fputs("Can't create output buffer\n", stderr);
  exit(EXIT_FAILURE); }