I was wondering the difference between puts() and printf() functions while using sleep() function.
Here is my code(In C language):
printf("hello, world");
sleep(1);
printf("Good, bye!");
After compiling and running the program, it seems that it will sleep first and then print "hello, worldGood, bye!"
However, if using puts() instead of printf(), it will print "hello, world" then sleep, and finally print "Good, bye".
puts("hello, world");
sleep(1);
puts("Good, bye!);
It's because
puts
is also outputting a newline character which, on devices that can be determined to be interactive, causes flushing by default (for standard output) (a).You should see a similar effect if your initial
printf
outputs a newline at the end:or if you
fflush (stdout);
before thesleep()
call.The relevant part of
C11
is7.21.3 Files
, section/7
:This harks back to the days of
C89/90 4.9.3 Files
:(a): It's not quite that simple. For starters, this is implementation dependent simply because the standard states that what constitutes an interactive device is implementation dependent (the behaviour is specified but not the thing that affects that behaviour).
Secondly (as per here), the standard only mandates when standard output becomes fully bufferd (when the device is definitely not interactive). Whether it's unbuffered or line buffered for interactive devices is an implementation decision.
From what I understand, printf will flush the stream if a newline
\n
is present. puts, I'm not really sure. It may be implementation dependant.Your sleep is just long enough for printf which is not containing a
\n
to flush the stream.I recommend you flush the stream when required with
fflush(stdout);
Then you can avoid the sleep altogether.This is because of buffering - by default, standard out buffers up to each new line.
printf()
does not include a newline, so output isn't flushed.puts()
includes a newline, so output is flushed.You can cause
printf()
to flush by putting a newline:or by calling
fflush()
directly:For more about buffering, see the man page for
setbuf()
: