Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing in the same line with a pause in C

I want to make my program to print something, then wait for a few seconds and then print something else in the same line. I've tried to write it as:

printf ("bla bla bla");
sleep (2);
printf ("yada yada yada\n");

but in the output I get to wait for 2 seconds and then I get the whole line printed as one. When I tried to put the output in different lines it did print with a pause.

How do I make it to print with a pause in the same line?

*Working on Linux

like image 890
SIMEL Avatar asked Apr 15 '11 17:04

SIMEL


2 Answers

printf ("bla bla bla");
fflush(stdout);
sleep (2);
printf ("yada yada yada\n");

fflush forces the stdout internal buffer to be flushed to the screen.

like image 102
GWW Avatar answered Nov 09 '22 13:11

GWW


The stdout is a line buffered stream by default, this means you need to explicitly flush it. It is implicitly flushed on newline. This behavior is mandated by the C99 standard.

This means in your first printf, the text is added to an internal buffer. This is done to improve efficiency, e.g. when printing lots of small text fragments.

Your second printf contains a newline, and that causes the stream to get flushed. You can explicitly flush stdout via fflush(stdout); if you want.

As an alternative you could also use the unbuffered stderr, as in fprintf(stderr, "bla bla bla");, but as its name implies it is intended for errors and warnings.

See also the SO question Why does printf not flush after the call unless a newline is in the format string?.

like image 30
DarkDust Avatar answered Nov 09 '22 13:11

DarkDust