Lawrence Kirby <lk****@netacti ve.co.uk> writes:
On Sun, 12 Dec 2004 22:39:14 -0600, Jack Klein wrote: On Sun, 12 Dec 2004 22:45:50 -0500, James McIninch
<ja************ *******@comcast .net> wrote in comp.lang.c:
[...] sp*********@hot mail.com wrote:
> How can I find the true EOF for a file that contains 0xFF. When I use
> fgetc and it encounters 0xFF it thinks it's the end of file but it
> really isn't.
<posted & mailed>
0xFF is never EOF. You simply:
char ch;
WRONG!
Not wrong.
Yes, wrong.
As Keith correctly pointed out, see this question in the FAQ:
http://www.eskimo.com/~scs/C-faq/q12.1.html
FILE *fp;
.
.
.
for (ch = fgetc(fp); !feof(fp); ch = fgetc(fp))
The code here doesn't use the value of ch to test for end of file, so ch
can be char, which appears to be the point the code is trying to make.
The code does contain a bug however because it fails to test ferror(). If
the fgetc() operation failed due to an error the loop would never
terminate, appearing to process multiple (char)EOF valued "characters ".
fgetc(fp) returns a value of type int; ch is of type char. The
assignment implicitly converts the int result to type char. If char
is signed, and if the value returned by fgetc(fp) is outside the range
CHAR_MIN..CHAR_ MAX, the conversion either yields an implementation-defined
value or raises an implementation-defined signal (C99 6.3.1.3p3).
This will happen either of fgetc() returns EOF or if it returns a
value greater than CHAR_MAX (but less than or equal to UCHAR_MAX).
Making ch an unsigned char might alleviate this, but of course the
correct solution is to use an int and check for ch==EOF.
--
Keith Thompson (The_Other_Keit h)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.