6

Possible Duplicate:
Why does printf not flush after the call unless a newline is in the format string? (in C)

I've a code like this:

printf("Starting nets allocation...");
while(...)
{
    ...some operations...
}
puts("DONE");

The code should prints immediately the string "Starting nets allocation..." then, after the loop, should prints "DONE".

Instead, the program performs first the loop and then prints the string "Starting nets allocation...DONE" why it happens? How can I resolve this?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Andrea Sylar Solla
  • 157
  • 1
  • 2
  • 10

2 Answers2

13

The output stream stdout is buffered by default, so if you want immediate output you'll need to flush the output stream - using fflush - or cause a newline to be printed in the printf:

printf("Starting nets allocation...");
fflush(stdout);    

Or:

printf("Starting nets allocation...\n");

Note that you can also control buffering at a file pointer level using the setbuf function from stdio.h:

setbuf(stdout, NULL);

The second argument to setbuf is a buffer supplied by the caller to be used for buffering output to the stream. Passing NULL indicates that buffering is to be disabled, and is equivalent to:

setvbuf(stdout, NULL, _IONBF, 0);

which also disables buffering on the specified stream.

See docs for setbuf here.

pb2q
  • 58,613
  • 19
  • 146
  • 147
  • fflush() is what I was searching for! Thanks! – Andrea Sylar Solla Aug 27 '12 at 21:54
  • Can you please explain what does it mean for the output to `stdout` to be buffered? – Mehdi Charife Apr 04 '23 at 15:51
  • 1
    Hi @MehdiCharife sorry for the late reply. Things like input/output are often _buffered_, meaning that data is collected into a fixed storage area before processing as a whole. This can be more efficient: operating on a buffer of characters instead of taking an action one character at a time. This is just one example of buffering. https://en.wikipedia.org/wiki/Data_buffer – pb2q Aug 16 '23 at 15:30
3

The output to stdout is buffered, so add

fflush(stdout); 

after the printf call to flush contents. Usually adding a newline character flushes the buffer too, but that may not be desirable in your case.

Praetorian
  • 106,671
  • 19
  • 240
  • 328