php feof用來識別文件末尾字符的方法
更新時間:2010年08月01日 19:12:04 作者:
程序需要一種標準的方式來識別何時到達文件的末尾.這個標準通常稱為文件末尾,或EOF字符。
EOF 是非常重要的概念,幾乎每種主流編程語言都提供了相應(yīng)的內(nèi)置函數(shù),來驗證解析器是否到達了文件EOF。在PHP 中,此函數(shù)是feof ()。feof ()函數(shù)用來確定是否到達資源末尾。它在文件I/O 操作中經(jīng)常使用。其形式為:
int feof(string resource)
實例如下:
<?php
$fh = fopen("/home/www/data/users.txt", "rt");
while (!feof($fh)) echo fgets($fh);
fclose($fh);
?>
bool feof ( resource $handle ):Tests for end-of-file on a file pointer
這個php manual上面的原話。
為了方便,我以前都是這樣使用的
<?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);
?>
確實,這樣使用比較簡單。但是,如果上面的變量$file不是一個合法的file pointer 或者已經(jīng)被fclose關(guān)閉了的話。
那么在程序的第六行出,就會產(chǎn)生一個waring,并發(fā)生死循環(huán)。
為什么?
原因就是
Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.
所以,為了安全起見,最好在使用上面代碼的時候 加個判斷,is_resource 還是比較安全的。
int feof(string resource)
實例如下:
復(fù)制代碼 代碼如下:
<?php
$fh = fopen("/home/www/data/users.txt", "rt");
while (!feof($fh)) echo fgets($fh);
fclose($fh);
?>
bool feof ( resource $handle ):Tests for end-of-file on a file pointer
這個php manual上面的原話。
為了方便,我以前都是這樣使用的
復(fù)制代碼 代碼如下:
<?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);
?>
確實,這樣使用比較簡單。但是,如果上面的變量$file不是一個合法的file pointer 或者已經(jīng)被fclose關(guān)閉了的話。
那么在程序的第六行出,就會產(chǎn)生一個waring,并發(fā)生死循環(huán)。
為什么?
原因就是
Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.
所以,為了安全起見,最好在使用上面代碼的時候 加個判斷,is_resource 還是比較安全的。
相關(guān)文章
PHP計算數(shù)組中值的和與乘積的方法(array_sum與array_product函數(shù))
這篇文章主要介紹了PHP計算數(shù)組中值的和與乘積的方法,結(jié)合實例形式較為詳細的分析了array_sum與array_product函數(shù)的功能與使用方法,需要的朋友可以參考下2016-04-04
PHP 頁面跳轉(zhuǎn)到另一個頁面的多種方法方法總結(jié)
如何在PHP中從一個頁面重定向到另外一個頁面呢?這里列出了三種辦法,供參考。2009-07-07

