Detect end of text file, reading using fgetc

给你一囗甜甜゛ 提交于 2019-12-23 02:24:07

问题


I have a text file. I am writing a program to read from the file using fgetc and put in a two dimensional buffer.

After printing the contents of file, it's printing some junk until end of buffer despite having put the check for EOF and ERROR as shown below. How can I get it done?

    unsigned char ch;
    while(ch=fgetc(fp))
    {
       if(ch== EOF || ch==NULL)
       break;
       //OTHER INSTRUCTIONS
    }

Thanks :)


回答1:


EOF is an Integer with the value -1.

When you do ch=fgetc(fp) in the while loop, you read into an unsigned char, that can by definition not be signed, so it can't be equal to -1.

A solution could be to read into an integer and to cast it after having checked for EOF.

int ch;
while(ch=fgetc(fp))
{
   if(ch == EOF)
   break;
   //OTHER INSTRUCTIONS
}

Refer to this for a sample of how it should be implemented.




回答2:


Your program has some errors.Use the following program,it is correct program to print all the data of any file:

#include<stdio.h>
#include<conio.h>
main()
{
    FILE *fp;
    char c;
    fp=fopen("filename.txt","r");
    clrscr();
    c=fgetc(fp);
    while(c!=EOF)
    {
        printf("%c",c);
        c=fgetc(fp);
    }
    getch();
}

I hope that it will help you



来源:https://stackoverflow.com/questions/23513961/detect-end-of-text-file-reading-using-fgetc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!