Home > Back-end >  Bosses told me why is to be repeated at the end of this code to print the last line, please explain
Bosses told me why is to be repeated at the end of this code to print the last line, please explain

Time:10-01

#include
#include
# define MAX 1024

Int main (void)
{
FILE *fp;
Char buffer (MAX);

If ((fp=fopen (" lines. TXT ", "w"))==NULL)
{
Printf (" failed to open the file! \n");
The exit (EXIT_FAILURE);
}
Fputs (" Line one: Hello World! \ n ", fp);
Fputs (" Line two: Hello Fishc! \ n ", fp);
The fputs (" Line three: I love Fishc.com! \ n ", fp);

The fclose (fp);

If ((fp=fopen (" lines. TXT ", "r"))==NULL)
{
Printf (" failed to open the file! \n");
The exit (EXIT_FAILURE);
}

while (! The feof (fp))
{
The fgets (buffer, MAX, fp);
Printf (" % s ", buffer);
}

return 0;
}

CodePudding user response:

 
Int ch;
while (! The feof (fp))
{
The fgets (buffer, MAX, fp);
Printf (" % s ", buffer);
Ch=fgetc (fp);
If (ch==1)
break;
}

"" C" language "feof () function returns the last" the content of the read operation ", for many years the "position and content" mixed, thus caused to the concept of specious,
So, the location and content exactly what's different? A simple example, such as someone said "you go to the train of the last section trunk" this is the place, and if "you have been walking backwards and touch to the end of the track," this is the content, that is judged by the content will be "how to go one day, this is totally dependent on" while (! The feof (FP)) {... } "for copying files, target document than the source document" some more "reasons,
In the "C" file read operations cannot be completely dependent on "while (! The feof (FP)) {... } "judgment,
More details, you can query baidu encyclopedia feof function

CodePudding user response:

 # include & lt; Stdio. H> 
#include

# define MAX 1024

Int main (void)
{
FILE *fp;
Char buffer (MAX);

If ((fp=fopen (" lines. TXT ", "w"))==NULL)
{
Printf (" failed to open the file! \n");
The exit (EXIT_FAILURE);
}
Fputs (" Line one: Hello World! \ n ", fp);
Fputs (" Line two: Hello Fishc! \ n ", fp);
The fputs (" Line three: I love Fishc.com! \ n ", fp);

The fclose (fp);

If ((fp=fopen (" lines. TXT ", "r"))==NULL) {
Printf (" failed to open the file! \n");
The exit (EXIT_FAILURE);
}

while (! The feof (fp))
{
If (the fgets (buffer, MAX, fp)==NULL)
break;
Printf (" % s ", buffer);
}
The fclose (fp);

return 0;
}

For your reference ~
  • Related