简体   繁体   中英

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++ . I'm worried about using while((c=fgetc())!=EOF) because:

What if the binary code of the file contains 11111111 which has same value as EOF and the program finishes unwantedly ?

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.

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. fgetc reads an unsigned char cast to an 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 . I don't know how exotic systems where sizeof(int) == 1 can deal with this.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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