使用fgetc时是否可能将EOF与常规字节值混淆? [英] Is it possible to confuse EOF with a normal byte value when using fgetc?

查看:117
本文介绍了使用fgetc时是否可能将EOF与常规字节值混淆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们经常这样使用fgetc:

int c;
while ((c = fgetc(file)) != EOF)
{
    // do stuff
}

从理论上讲,如果文件中的一个字节的值为EOF,则此代码有错误-将尽早中断循环并无法处理整个文件.这种情况可能吗?

Theoretically, if a byte in the file has the value of EOF, this code is buggy - it will break the loop early and fail to process the whole file. Is this situation possible?

据我了解,fgetc在内部将从文件读取的字节转换为unsigned char,然后转换为int,然后将其返回.如果int的范围大于unsigned char的范围,则将起作用.

As far as I understand, fgetc internally casts a byte read from the file to unsigned char and then to int, and returns it. This will work if the range of int is greater than that of unsigned char.

如果不是(可能是sizeof(int)=1),会发生什么?

What happens if it's not (probably then sizeof(int)=1)?

  • fgetc有时会从文件中读取等于EOF的合法数据吗?
  • 会更改从文件读取的数据以避免单个值EOF吗?
  • fgetc会成为未实现的功能吗?
  • EOF是否会是其他类型,例如long?
  • Will fgetc read a legitimate data equal to EOF from a file sometimes?
  • Will it alter the data it read from the file to avoid the single value EOF?
  • Will fgetc be an unimplemented function?
  • Will EOF be of another type, like long?

我可以通过额外的检查使代码变得万无一失:

I could make my code fool-proof by an extra check:

int c;
for (;;)
{
    c = fgetc(file);
    if (feof(file))
        break;
    // do stuff
}

是否需要最大的便携性?

It is necessary if I want maximum portability?

推荐答案

是的,c = fgetc(file); if (feof(file))确实可以最大程度地提高可移植性.通常,当unsigned charint具有相同数量的唯一值时,也可以使用.在具有charsigned charunsigned charshortunsigned shortintunsigned的罕见平台上,都使用相同的位宽和范围宽度.

Yes, c = fgetc(file); if (feof(file)) does work for maximum portability. It works in general and also when the unsigned char and int have the same number of unique values. This occurs on rare platforms with char, signed char, unsigned char, short, unsigned short, int, unsigned all using the same bit width and width of range.

请注意,feof(file))是不够的.代码还应该检查ferror(file).

Note that feof(file)) is insufficient. Code should also check for ferror(file).

int c;
for (;;)
{
    c = fgetc(file);
    if (c == EOF) {
      if (feof(file)) break;
      if (ferror(file)) break;
    }
    // do stuff
}

这篇关于使用fgetc时是否可能将EOF与常规字节值混淆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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