Use Feof () to determine why the content will be more output at the end of the file

Source: Internet
Author: User

This is the original code:

#include <stdio.h>
int main ()
{
FILE * FP;
int ch;
fp = fopen ("D:\\aaaaa\\1.txt", "R");
while (!feof (FP))
{
ch = getc (FP);
Putchar (CH);
}
Fclose (FP);
return 0;
}

When you output it, you'll see that the output has a "space" in the end.

This is the improved code:

#include <stdio.h>
int main ()
{
FILE * FP;
int ch;
fp = fopen ("D:\\aaaaa\\1.txt", "R"); http://i.cnblogs.com/EditPosts.aspx?opt=1
while (ch = getc (FP),!feof (FP))
{
Putchar (CH);
}
Fclose (FP);
return 0;
}

Will find that the improved code will output the contents of the file normally, and will not add anything extra at the end.

Data found that the C language feof () function returned the last "read operation content." In the not-improved code, the while loop determines what fgetc () obtained in the last loop, which explains why the non-improved code will output "content" at the end.

Use Feof () to determine why the content will be more output at the end of the file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.