Search code examples
csleepputs

Difference between puts() and printf() in C while using sleep()


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

Solution

  • 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:

    printf("hello, world\n");
    

    or by calling fflush() directly:

    fflush(stdout);
    

    For more about buffering, see the man page for setbuf():

    The three types of buffering available are unbuffered, block buffered, and
       line buffered.  When an output stream is unbuffered, information appears on
       the destination file or terminal as soon as written; when it is block 
       buffered many characters are saved up and written as a block; when it 
       is line buffered characters are saved up until a newline is output or input
       is read from any stream attached to a terminal device (typically stdin).
       ....
       If a stream refers to a terminal (as stdout normally does) it is 
       line buffered. 
       ....
       The standard error stream stderr is always unbuffered by default.