Fgets, gets and fputs, puts

  

We know that both functions provide the ability to enter one line at a time. However, gets is a deprecated function. The reason is that you can't specify the length of the buffer using gets, which may cause the buffer to overflow. In addition to the fact that only the standard input (stdin) can be manipulated, there is another difference between gets and fgets ——gets does not read newline characters into the buffer. For example: enter ”abcde\ ”, then only use ”abcde” in the buffer when getting, and not ”\ ”. In contrast, fgets will be read in full by ”abcde\ ”.
Correspondingly, puts are generally used in pairs with gets, so puts output a string ending in NULL (NULL does not output), and will also output a newline to standard output.
We will first look at the following block:
Program 1:
char buf[BUFSIZE];
while( fgets(buf,BUFSIZE,stdin)!=NULL )
if( fputs( Buf,stdout)==EOF )
printf("output error!\ ");
Output:
Conclusion: fgets and fputs work together normally
Analysis: Input”abcdef\\ n”,fgets read in ”abcdef\ ” to the buffer, fputs will “abcdef\ ” take the output out of the buffer.
Program 2:
char buf[BUFSIZE];
while( gets(buf)!=NULL )
if( puts(buf)==EOF )
printf("output Error!\ ");
Output:
Conclusion: The combination of gets and puts works normally
Analysis: Input”abcdef\ ”,gets read in”abcdef”to the buffer (note: Don't read in & rsquo;\ ’), puts will take the output from the buffer, and then output a newline (‘\ ’) to the standard output, ie gets does not read the newline, and Puts adds a newline character.
Program 3:
char buf[BUFSIZE];
while( gets(buf)!=NULL )
if( fputs(buf,stdout)==EOF )
printf(" ;output error!\ ");
Output:
Conclusion: The combination of gets and fputs does not work properly
Analysis: Input”abcdef\ ”,gets read”abcdef”to buffer (Note: do not read in & rsquo; \\ n & rsquo;), fputs will "take the output from the buffer (with no newline added), the input of the following line will be on the same line as the previous output, resulting in output One less line break than the input.
Program 4:
char buf[BUFSIZE];
while( fgets(buf,BUFSIZE,stdin)!=NULL )
if( puts(buf)==EOF )
printf ("output error!\ ");
Output:
Conclusion: The combination of fgets and puts does not work properly
Analysis: Input”abcdef\ ”,fgets read in”abcdef\ ” In the buffer, puts will take the output from the buffer (there is already a newline here), and then output a newline, so that the output has one newline than the input (output two newlines) ).

Summary: should try to use fgets and fputs, on the one hand is relatively safe, on the one hand intact two of the inputs and outputs, do not have to remember to deal with line breaks.

Copyright © Windows knowledge All Rights Reserved