Beruflich Dokumente
Kultur Dokumente
s, hopefully this explanation will help you understand better. Before I go into
too much detail about what EOF is, I'll tell you what it isn't.
EOF is NOT:
A char
A value that exists at the end of a file
A value that could exist in the middle of a file
And now to what it actually is.
EOF is a macro defined as an int with a negative value. It is normally returned
by functions that perform read operations to denote either an error or end of in
put. Due to variable promotion rules (discussed in detail later), it is importan
t to ensure you use an int to store the return code from these functions, even i
f the function appears to be returning a char, such as getchar() or fgetc().
Here are some code examples that you might use:
int c;
while ((c = fgetc(fp)) != EOF)
{
putchar (c);
}
int ch;
while ((ch = cin.get()) != EOF)
{
cout <<(char)ch;
}
The "char to int promotion" table makes it clear that the sign of a char produce
s a very different number in the int.
So what does all this mean to me as a programmer?
Well, let's have a look at a revised version of the code shown above, this time
incorrectly using a char variable to store the return code from fgetc().
char c;
while ((c = fgetc(fp)) != EOF)
{
putchar (c);
}
Now let's assume that within the file we are reading from is a byte with value 0
xff. fgetc() returns this value within an int, so it looks like this: 0x00 0xff
(again, I'm assuming 2 byte ints). To store this value in a char, it must be dem
oted, and the char value becomes 0xff.
Next, the char c is compared with the int EOF. Promotion rules apply, and c must
be promoted to an int. However, in the sample code, the sign of c isn't explici
tly declared, so we don't know if it's signed or unsigned, so the int value coul
d become either 0xff 0xff or 0x00 0xff. Therefore, the code is is not guaranteed
to work in the way we require.
The following is a short program to help show the promotion:
#include <stdio.h>
int main(void)
{
int i = -1;
signed char sc = 0xff;
unsigned char usc = 0xff;
printf ("Comparing %x with %x\n", i, sc);
if (i == sc) puts("i == sc");
else puts("i != sc");
putchar ('\n');
printf ("Comparing %x with %x\n", i, usc);
if (i == usc) puts("i == usc");
else puts("i != usc");
return 0;
}
/*
* Output
Comparing ffff with ffff <--- Notice this has been promoted
i == sc
Comparing ffff with ff
i != usc
*
*/
Another scenario to consider is where the char is unsigned. In this case, the pr
ocess of demoting and promoting the returned value from fgetc() will have the af
fect of corrupting the EOF value, and the program will get stuck in a infinite l
oop. Let's follow that process through:
#include <stdio.h>
int main(void)
{
FILE *fp;
unsigned char c;
if ((fp = fopen("myfile.txt", "rb")) == NULL)
{
perror ("myfile.txt");
return 0;
}
while ((c = fgetc(fp)) != EOF)
{
putchar (c);
}
fclose(fp);
return 0;
}