简体   繁体   English

有没有更安全的 EOF 替代品? 它在我的情况下不起作用

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

I'm working on my school project in which I've got to handle files in c/c++ .我正在处理我的学校项目,我必须在其中处理 c/c++ 中的文件。 I'm worried about using while((c=fgetc())!=EOF) because:我担心使用while((c=fgetc())!=EOF)因为:

What if the binary code of the file contains 11111111 which has same value as EOF and the program finishes unwantedly ?如果文件的二进制代码包含与 EOF 具有相同值的11111111并且程序意外完成怎么办?

here is a sample code in which I first create a binary code containing -1 and the program finishes before indeed reaching end of file.这是一个示例代码,其中我首先创建一个包含-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;
}

could anyone help me with this please??有人可以帮我吗??

EOF is a (macro for a) negative int. EOF是一个(宏)负整数。 fgetc reads an unsigned char cast to an int. fgetc读取转换为 int 的无符号字符。 As long as the range of unsigned char is smaller than that of int, such conversion never results in a negative number, in which case there is no overlap with EOF .只要 unsigned char 的范围小于 int 的范围,这种转换永远不会导致负数,在这种情况下,与EOF没有重叠。 I don't know how exotic systems where sizeof(int) == 1 can deal with this.我不知道 sizeof(int) == 1 的奇异系统如何处理这个问题。

But in your attempt, you're comparing the result of the assignment operation, which is lvalue to the left hand operand, which is a char converted from int.但是在您的尝试中,您将赋值操作的结果(左值)与左操作数(从 int 转换为字符)进行比较。 And as such, your concern is valid.因此,您的担忧是有道理的。

To fix the program, read the input into an int variable, compare that with EOF , and then convert to char.要修复程序,请将输入读入 int 变量,将其与EOF进行比较,然后转换为 char。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM