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

Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <b> <quote> <pre> <hr> <br> <p> <img> <blockquote> <font> <tt> <table> <tr> <i>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options

speck-geostationary