天天看點

feof函數的用法 php,php feof函數用法與注意事項

fopen() 或 fsockopen() 成功打開(但還沒有被 fclose() 關閉)的檔案。

$file = fopen("test.txt", "r");

//輸出文本中所有的行,直到檔案結束為止。

while(! feof($file))

{

echo fgets($file). "

";

}

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";

}

其中當讀取行數包括檔案結尾的時候,$result數組中總會比期望的内容多出來一個元素:

(boolean)false

按說,如果讀取到最後一行,feof函數會傳回TRUE,然後while循環就退出了,為什麼不是呢?

1

while (!feof($hd)) {

事情原來是這樣子的:

// 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);

?>

提示和注釋

提示:feof() 函數對周遊長度未知的資料很有用。

注意:如果伺服器沒有關閉由 fsockopen() 所打開的連接配接,feof() 會一直等待直到逾時而傳回 TRUE。預設的逾時限制是 60 秒,可以使用 stream_set_timeout() 來改變這個值。

注意:如果傳遞的檔案指針無效可能會陷入無限循環中,因為 EOF 不會傳回 TRUE。