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

I was interested to know the difference between puts () and printf () when using the 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 she will first sleep , and then type "hello, worldGood, bye!"

However, if puts () is used instead of printf (), it will print "hello, world" and then sleep and finally print "Good, bye".

puts("hello, world");
sleep(1);
puts("Good, bye!);
+5
source share
3 answers

- - . printf() , . puts() , .

printf() , :

printf("hello, world\n");

fflush():

fflush(stdout);

. 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.
+7

, puts , , , ( ) (a).

, printf :

printf("hello, world\n");

fflush (stdout); sleep().

C11 7.21.3 Files, /7:

- ( ), ( ) ( ). , ; , , .

C89/90 4.9.3 Files:

- ( ), ( ) ( ). ; , , .


(a): . , , , , , ( , , ).

- ( ), , bufferd ( ). - .

+9

, , printf , \n. , . .

printf, \n, .

, fflush(stdout);. .

0

All Articles