There are two methods to determine the end of a file: EOF and feof ()
View stdio. h and you can see the following definitions:
# Define EOF (-1)
# DEFINE _ ioeof 0x0010
# Define feof (_ stream)-> _ flag & _ ioeof)
we can see that the two methods have different principles.
it is said that EOF can only be used in text files. Otherwise, the type of the defined variable must be viewed. The following Program can be used for both text and binary files:
int C;
while (C = fgetc (FP ))! = EOF)
{< br> printf ("% x \ n", c);
}
If FF is read, because C is defined as int type, in fact C = 0x000000ff is not equal to EOF (-1 = 0 xffffffff), so it will not be mistaken as the end of the file.
However, if C is defined as char, obfuscation may occur.
Char C;
While (C = fgetc (FP ))! = EOF)
{
Printf ("% x \ n", C );
}
Because an ascii code is stored in a text file, and FF in the ASCII Code represents a null value (blank), it is generally not used, so if the read file returns ff, the end of the text file is reached. However, if it is a binary file, which may contain ff, you cannot use the read EOF as the condition for end of the file. At this time, you can only use the feof () function.
In VC, only when the file position pointer (FP-> _ PTR) reaches the end of the file and then the read/write operation occurs, the flag (FP-> _ flag) to include _ ioeof. Then call feof () to obtain the end information of the file. Therefore, if you run the following program:
Char C;
While (! Feof (FP ))
{
C = fgetc (FP );
Printf ("% x \ n", C );
}
One more ffffffff is output, because after reading the last character, FP-> flag is still not set to _ ioeof, so feof () still does not detect the end of the file. Feof () cannot detect the end of a file until fgetc () is called again. In this way, one more-1 (fffffff) is output ).
The correct statement should be:
Char C;
C = fgetc (FP );
While (! Feof (FP ))
{
Printf ("% x \ n", C );
C = fgetc (FP );
}
In fact, feof () can be replaced by EOF? No, there is another problem. When fgetc returns-1, there are two situations: Reading the end of a file or reading an error. Therefore, we are not sure that the file has ended, because it may be a read error! In this case, we need feof ().