login
Header Space

 
 

How to Differentiate between EOF and a Character whose ASCII code is 255

June 1, 2008 - 11:05am
Submitted by Eus on June 1, 2008 - 11:05am.

A call to fgetc() or getchar() will return EOF if the end-of-file has been reached.
As far as I know, GNU C Library defines EOF to be (-1).

Those who are unwary will think that those functions return a char.
Now a char has a range from 0x00 to 0xFF because its size is one byte.
However, if EOF is returned as a char, which must take one value from the range, there will be no way to differentiate whether or not the returned char is actually a byte read from the stream or EOF to signal that the end-of-file has been reached already.

Those functions actually return an int.
This way, EOF in a 32-bit machine can assume one value from 0x00000100 to 0xFFFFFFFF, inclusive.
Whereas, one byte taken from the stream can only assume one value from 0x00000000 to 0x000000FF, inclusive.
Therefore, EOF can be differentiated from one byte read from the stream.

This fact implies that, if one would like to detect EOF with a statement like if (ch != EOF) {...}, ch must be defined as an int not a char.

Archive: All about C Programming

Don't use the return from

July 15, 2008 - 10:43pm
Anonymous (not verified)

Don't use the return from fgetc() to check for eof. Instead use feof(), like this:

FILE *fp;
fp = fopen("filename","r");
while (!feof(fp)) {
  int ch;
  ch = fgetc(fp);
  // ...
}

As you pointed out, ch is an int, not a char. If you want to read it into a char array, you should probably use fread() instead of fgetc().

while (!feof(fp)) Is Redundant

July 23, 2008 - 10:59am

Hi Ho!

Don't use the return from fgetc() to check for eof. Instead use feof(), like this:

FILE *fp;
fp = fopen("filename","r");
while (!feof(fp)) {
  int ch;
  ch = fgetc(fp);
  // ...
}

IMO, this technique is not good because you still have to test whether or not ch actually is an EOF.

In other words, definitely your piece of code should look like the following one:

while (!feof(fp)) {
  int ch;
  ch = fgetc(fp);
  if (ch == EOF) { // We definitely do not want to process EOF, do we?
    break;
  }
  // ...
}

Therefore, the use of feof() is useless here and the code can be reduced to:

while (1) {
  int ch;
  ch = fgetc(fp);
  if (ch == EOF) {
    break;
  }
  // ...
}

Testing for ch == EOF is better than testing for !feof(fp) because the overhead of a function call is avoided here.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
speck-geostationary