Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"printf" doesn't print a string immediately [duplicate]

Tags:

c

printf

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?

like image 754
Andrea Sylar Solla Avatar asked Dec 09 '22 21:12

Andrea Sylar Solla


2 Answers

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.

like image 51
pb2q Avatar answered Dec 23 '22 22:12

pb2q


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.

like image 24
Praetorian Avatar answered Dec 23 '22 21:12

Praetorian