Given the precise way this particular code has been written, c
wouldn't need to be of type int
--it would still work if c
were of type char
.
Most code that reads characters from a file should (at least initially) read those characters into an int
though. Specifically, part of the basic design of C-style I/O is that functions like getc
and fgetc
can return EOF in addition to any value that could have come from the file. That is to say, any value of type char
could be read from the file. getc
, fgetc
, etc., can signal the end of file by returning at least one value that won't/can't have come from the file. It's usually -1, but that's not guaranteed. When char
is signed (which it usually is, nowadays) you can get a value from the file that will show up as -1 when it's been assigned to a char
, so if you're depending on the return value to detect EOF, this can lead to mis-detection.
The code you've included in the question simply copies the contents of the file to standard output, one character at a time. Making use of the EOF return value, we can simplify the code a little bit, so the main loop looks like this:
int c;
while (EOF != (c = fgetc(fp)))
printf("%c", c); // or: putchar(c);
I suppose some might find this excessively terse. Others may object to the assignment inside the condition of the loop. I, at least, think those are reasonable and valid arguments, but this still fits enough better with the design of the library that it's preferable.
fgetc
, it returns anint
(with good reason), so assigning that result to anint
is also a good idea. – Kissiec
is of typeint
, not "integer". The word "integer" covers all the integer types, fromchar
up tolong long
(and their unsigned variants). – Seabrook