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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With