write() to stdout and printf output not interleaved?

Printf is buffered.

You can force printf to ‘flush’ its buffer using the fflush call:

#include <stdio.h>
#define MAXLEN 256

int main() {
  int n;
  char buf[MAXLEN];
  while((n = read(0,buf,sizeof(buf))) != 0){
    printf("n: %d:",n);
    fflush(stdout); /* force it to go out */
    write(1,buf,n);
  }
  return 1;
}

In general, printf() being buffered is a good thing. Unbuffered output, particularly to visible consoles that require screen updates and such, is slow. Slow enough that an application that is printf’ing a lot can be directly slowed down by it (especially on the Windows platform; Linux and unixes are typically impacted less).

However, printf() being buffered does bite you if you also fprintf(stderr,) – stderr is deliberately unbuffered. As a consequence, you may get your messages with some printf() missing; if you write to another FILE handle that is also associated with the terminal, and might be unbuffered, make sure you first explicitly fflush(stdout).

Leave a Comment