tags:

views:

2984

answers:

7

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

+1  A: 

stdout is buffered, so will only output after a newline is printed.

To get immediate output, either:

  1. Print to stderr.
  2. Make stdout unbuffered.
Douglas Leeder
+3  A: 

To immediately flush call fflush(stdout) or fflush(NULL) (NULL means flush everything).

Aaron
+1  A: 

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.

Rasmus Kaj
+11  A: 

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);
Rudd Zwolinski
Or, to disable buffering entirely: `setbuf(stdout, NULL);`
Andy Ross
Thanks Andy, I added that option to the post.
Rudd Zwolinski
+2  A: 

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.

Southern Hospitality
A: 

by default, stdout is line buffered, stderr is none buffered and file is completely buffered.

woso
A: 

Note: Microsoft runtime libraries do not support line buffering, so printf("will print immediatelly to terminal"):

http://msdn.microsoft.com/en-us/library/86cebhfs.aspx

Renato