EOF有更安全的替代方案吗?它在我的情况下不起作用

Is there a safer alternative for EOF? It's not working in my case

本文关键字:我的 不起作用 情况下 方案 安全 EOF      更新时间:2023-10-16

我正在做我的学校项目,我必须在其中处理 c/c++ 中的文件。 我担心使用while((c=fgetc())!=EOF),因为:

如果文件的二进制代码包含与EOF具有相同值的11111111并且程序意外完成怎么办?

这是一个示例代码,其中我首先创建一个包含-1的二进制代码,程序在真正到达文件末尾之前完成。

int main()
{
FILE *p;
fopen_s(&p, "my.binn", "wb");
char c;
char result;
for (int t = 0; t < 3; t++)
{ //putting some bytes in file
result = 0;
for (int r = 0; r < 8; r += 2)
{
result |= (1 << (7 - r));
}
putc(result, p);
}
result = 0;
for (int r = 0; r < 8; r++)
{ //putting a byte of 11111111
result |= (1 << (7 - r));
}
putc(result, p);
for (int t = 0; t < 3; t++)
{ //again putting some bytes in file
result = 0;
for (int r = 0; r < 8; r += 2)
{
result |= (1 << (7 - r));
}
putc(result, p);
}
fclose(p);
fopen_s(&p, "my.binn", "rb");
while ((c = fgetc(p)) != EOF)
{ //here this loop was expected to continue until end of file(7 bytes) but it prints only three stars
cout << "*";
}
fclose(p);
return 0;
}

谁能帮我解决这个问题??

EOF是一个(宏为a(负整数。fgetc将一个无符号的字符转换为整数。只要无符号字符的范围小于 int 的范围,这种转换永远不会导致负数,在这种情况下,与EOF没有重叠。我不知道 sizeof(int( == 1 的奇特系统如何处理这个问题。

但是在您的尝试中,您正在比较赋值操作的结果(左值(和左侧操作数(从 int 转换的字符(。因此,您的担忧是有道理的。

要修复程序,请将输入读入 int 变量,将其与EOF进行比较,然后转换为 char。