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!);
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():