Hitopopamus
Hitopopamus

Reputation: 95

How to read a non-text file containing EOF characters in C?

I'm trying to loop over all bytes of a file using a simple while loop, like so:

char c = fgetc(InputFile);

while (c != EOF)
    {
        doStuff(c)
        c = fgetc(InputFile);
    }

However, when working with non-text files, I've found that some of the bytes within the file (that aren't the last one) contain the value 255, and therefore register as EOF and the while loop ends prematurely.

How do I get around this and loop over all bytes?

Upvotes: 1

Views: 90

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51845

As mentioned in the comments, you should assign the value returned by fgetc to an int variable, not a char. That way, you will be able to distinguish between a successfully input character that has the hex value 0xFF (fgetc will return 255) and a end-of-file condition (fgetc will return EOF, which is -1).

From the cppreference page for fgetc:

On success, returns the obtained character as an unsigned char converted to an int. On failure, returns EOF.

Upvotes: 1

Related Questions