检测文本文件结尾,使用fgetc读取 [英] Detect end of text file, reading using fgetc

查看:96
本文介绍了检测文本文件结尾,使用fgetc读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件。我正在编写一个程序,以使用 fgetc 从文件中读取内容,并将其放入二维缓冲区中。

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

打印文件内容后,尽管已经检查了EOF和ERROR,但仍会打印一些垃圾直到缓冲区末尾,如下所示。我该怎么办?

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
    }

谢谢:)

推荐答案

EOF 是一个整数,值 -1

在while循环中执行 ch = fgetc(fp)时,您会阅读放入未签名的字符,根据定义,该字符不能被签名,因此不能等于 -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.

一种解决方案可能是将整数读入并检查 EOF 后将其转换为整数。

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
}

请参阅://www.tutorialspoint.com/c_standard_library/c_function_fgetc.htm rel = nofollow>此

这篇关于检测文本文件结尾,使用fgetc读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆