Kevin Dong Kevin Dong - 3 months ago 11
C Question

What will happen if fgetc reads 0xFF?

fgetc
reads a character from a file at a time, and returns the character as type of
int
. If the file ends, then
fgetc
returns
EOF
("probably"
(int)(-1)
). However, I have seen this so frequently:

char ch;

while ((ch = fgetc(fp)) != EOF) { /* Do something. */ }
|<-- PARN -->|


This is what I concern:


  1. fgetc
    reads
    OxFF
    and returns
    0x000000FF
    .

  2. 0xFF
    is assigned to
    ch
    . (type casting from
    int
    to
    char
    )

  3. If
    PARN
    is type of
    char
    , then it will be promoted to
    0xFFFFFFFF
    .

  4. Break out of the while loop because
    PARN == EOF
    . (stop reading from the file)



How can we tell reading
OxFF
and returning
EOF
apart?

R.. R..
Answer

The whole reason the return type of fgetc is int is because it can return either a value of an unsigned char, or EOF. This is clearly documented in the specification and in any good resource on learning C. If you use an object of type char to store the result, this is programmer error.

Comments