Php Tutorial feof function usage and precautions
The eof () function checks whether it has reached the end of the file (eof ).
If the file pointer reaches EOF or an error occurs, TRUE is returned. Otherwise, an error (including socket timeout) is returned. Otherwise, FALSE is returned.
Syntax
Feof (file)
Parameter description
File is required. Specifies the file to be checked.
Description
The file parameter is a file pointer. The file pointer must be valid and point to a file that is successfully opened (but not closed) by fopen () or fsockopen.
<? Php
$ File = fopen ("test.txt", "r ");
// Output all rows in the text until the end of the file.
While (! Feof ($ file ))
{
Echo fgets ($ file). "<br/> ";
}
Fclose ($ file );
?>
If (file_exists ($ pmr_config ["datasetfile"]) {
$ Tmp_counter = 0;
$ Hd = fopen ($ pmr_config ["datasetfile"], "r ");
If ($ hd! = FALSE ){
While (! Feof ($ hd )){
$ Buffer = fgets ($ hd );
If ($ tmp_counter >=$ seq ){
$ Result [] = $ buffer;
}
$ Tmp_counter ++;
If ($ tmp_counter >=$ seq + $ size ){
Break;
}
}
} Else {
Echo "warning: open file {$ pmr_config [" datasetfile "]} failed! PHP_EOL ";
}
} Else {
Echo "warning: file {$ pmr_config [" datasetfile "]} does not exsits! PHP_EOL ";
}
When the number of read rows includes the end of the file, the $ result array always has one more element than expected:
(Boolean) false
In other words, if the last row is read, the feof function returns TRUE, and the while loop exits. Why not?
1
While (! Feof ($ hd )){
It turns out to be like this:
<? Php
// If file can not be read or doesn't exist fopen function returns FALSE
$ File = @ fopen ("no_such_file", "r ");
// FALSE from fopen will issue warning and result in infinite loop here
While (! Feof ($ file )){
}
Fclose ($ file );
?>
Feof () is, in fact, reliable. However, you have to use it carefully in conjunction with fgets (). A common (but incorrect) approach is to try something like this:
<?
$ Fp = fopen ("myfile.txt", "r ");
While (! Feof ($ fp )){
$ Current_line = fgets ($ fp );
// Do stuff to the current line here
}
Fclose ($ fp );
?>
Tips and comments
Tip: The feof () function is useful for traversing data with unknown length.
Note: If the server does not close the connection opened by fsockopen (), feof () will wait until it times out and return TRUE. The default timeout limit is 60 seconds. You can use stream_set_timeout () to change this value.
Note: If the passed file pointer is invalid, it may be in an infinite loop, because EOF does not return TRUE.