Why does printf not flush after the call unless a newline is in the format string? (in C)
Is this POSIX behavior?
How might I have printf immediately flush every time?
Thanks, Chenz
Why does printf not flush after the call unless a newline is in the format string? (in C)
Is this POSIX behavior?
How might I have printf immediately flush every time?
Thanks, Chenz
stdout is buffered, so will only output after a newline is printed.
To get immediate output, either:
To immediately flush call fflush(stdout) or fflush(NULL) (NULL means flush everything).
You can fprintf to stderr, which is unbuffered, instead. Or you can flush stdout when you want to. Or you can set stdout to unbuffered.
The stdout
stream is buffered, 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 stderr instead using fprintf
:
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);
It's probably like that because of efficiency and because if you have multiple programs writing to a single TTY, this way you don't get characters on a line interlaced. So if program A and B are outputting, you'll usually get:
program A output
program B output
program B output
program A output
program B output
This stinks, but it's better than
proprogrgraam m AB ououtputputt
prproogrgram amB A ououtputtput
program B output
Note that it isn't even guaranteed to flush on a newline, so you should flush explicitly if flushing matters to you.
by default, stdout is line buffered, stderr is none buffered and file is completely buffered.
Note: Microsoft runtime libraries do not support line buffering, so printf("will print immediatelly to terminal"):