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?
The output stream
stdoutis buffered by default, so if you want immediate output you’ll need to flush the output stream – usingfflush– or cause a newline to be printed in theprintf:Or:
Note that you can also control buffering at a file pointer level using the
setbuffunction from stdio.h:The second argument to
setbufis 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:which also disables buffering on the specified stream.
See docs for
setbufhere.