fgetc读取值为-1的字符 [英] fgetc reads character with value = -1

查看:414
本文介绍了fgetc读取值为-1的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

fgetc()函数读取Ubuntu文本文件中的字符。



EoF之前的最后一个字符是code = -1。

这到底是什么?
在文本编辑器文件中似乎没问题,最后没有奇怪的符号。

  while(!feof(fp))
{
c = fgetc(fp);
printf(%c%i\\\
,c,c); //
}


解决方案

feof 旨在表明您已尝试阅读过去文件的结尾 - 这意味着你首先必须达到它。所以它只会在您尝试阅读并且系统意识到您最后才会起作用。如果您尝试读取文件末尾, fgetc 会返回什么结果? EOF (方便, -1 - 这就是为什么 fgetc 返回一个 int ,而不是 char )。

所以发生什么是你进入循环 - 因为你还没有试图在最后读过去 - 并且调用返回-1的 fgetc ,因为你试图阅读超过文件的末尾。下一次循环时, feof 会告诉你,你已经达到了文件的末尾,并尝试读取它,然后你就会发现它。



您应该阅读您打算使用的函数的文档: feof fgetc 文档解释这一点。但即使他们没有,一个简单的谷歌搜索会回答你的问题:为什么是while(!feof(file))总是错的?


fgetc() function reads characters from a text file in Ubuntu.

the last character before EoF is with code = -1.

what the heck is that? in text editor file seems ok, no strange symbols at end.

while (!feof(fp))
{
    c = fgetc(fp);
    printf("%c %i\n", c, c);//
}

解决方案

feof is meant to signal that you've tried to read past the end of file - which means that you first have to reach it. So it will only work after you try to read and the system realizes you're at the end. And what does fgetc return if you try to read past the end of file? EOF (conveniently, -1 - which is why fgetc returns an int instead of a char).

So what's happening is that you enter the loop - because you haven't yet tried to read past at the end yet - and call fgetc which returns -1 because you tried to read past the end of the file. The next time around the loop, feof tells you that you've already hit the end of the file and tried to read past it and you break out.

You should read the documentation of functions you intend to use: feof and fgetc documentation explain this. But even if they did not, a simple google search would have answered your question: Why is "while ( !feof (file) )" always wrong?.

这篇关于fgetc读取值为-1的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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