Why does printf not flush after the call unless a newline is in the format string?

Crazy Chenz picture Crazy Chenz · Nov 11, 2009 · Viewed 372.2k times · Source

Why does printf not flush after the call unless a newline is in the format string? Is this POSIX behavior? How might I have printf immediately flush every time?

Answer

Rudd Zwolinski picture Rudd Zwolinski · Nov 11, 2009

The stdout stream is line buffered by default, so will only display what's in the buffer after it reaches a newline (or when it's told to). You have a few options to print immediately:

Print to stderrinstead using fprintf (stderr is unbuffered by default):

fprintf(stderr, "I will be printed immediately");

Flush stdout whenever you need it to using fflush:

printf("Buffered, will be flushed");
fflush(stdout); // Will now print everything in the stdout buffer

Edit: From Andy Ross's comment below, you can also disable buffering on stdout by using setbuf:

setbuf(stdout, NULL);

or its secure version setvbuf as explained here

setvbuf(stdout, NULL, _IONBF, 0);