0

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?

Kevin Dong
  • 5,001
  • 9
  • 29
  • 62

3 Answers3

3

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.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • I got it. When I saw such code in other [thread](http://stackoverflow.com/questions/30213308/file-pointers-behave-differently-when-passed-to-functions-why), I thought that it is wrong, so I ask here and check whether it is correct or not. Thanks a lot. ;-) – Kevin Dong Sep 02 '16 at 04:30
1

Yes, your concern is correct that the value gets typecast to char before the comparison is made.

The easiest solution is:

int chread;
while ((chread = fgetc(fp)) != EOF) { char ch = chread; /* Do something. */ }
J Earls
  • 1,792
  • 8
  • 12
0

fgetc() returns the obtained character on success or EOF on failure.

If the failure has been caused by end-of-file condition, additionally sets the eof indicator (see feof()) on stream. If the failure has been caused by some other error, sets the error indicator (seeferror() ) on stream.

Shravan40
  • 8,922
  • 6
  • 28
  • 48