php feof用來(lái)識(shí)別文件末尾字符的方法
更新時(shí)間:2010年08月01日 19:12:04 作者:
程序需要一種標(biāo)準(zhǔn)的方式來(lái)識(shí)別何時(shí)到達(dá)文件的末尾.這個(gè)標(biāo)準(zhǔn)通常稱為文件末尾,或EOF字符。
EOF 是非常重要的概念,幾乎每種主流編程語(yǔ)言都提供了相應(yīng)的內(nèi)置函數(shù),來(lái)驗(yàn)證解析器是否到達(dá)了文件EOF。在PHP 中,此函數(shù)是feof ()。feof ()函數(shù)用來(lái)確定是否到達(dá)資源末尾。它在文件I/O 操作中經(jīng)常使用。其形式為:
int feof(string resource)
實(shí)例如下:
<?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
這個(gè)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);
?>
確實(shí),這樣使用比較簡(jiǎn)單。但是,如果上面的變量$file不是一個(gè)合法的file pointer 或者已經(jīng)被fclose關(guān)閉了的話。
那么在程序的第六行出,就會(huì)產(chǎn)生一個(gè)waring,并發(fā)生死循環(huán)。
為什么?
原因就是
Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.
所以,為了安全起見(jiàn),最好在使用上面代碼的時(shí)候 加個(gè)判斷,is_resource 還是比較安全的。
int feof(string resource)
實(shí)例如下:
復(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
這個(gè)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);
?>
確實(shí),這樣使用比較簡(jiǎn)單。但是,如果上面的變量$file不是一個(gè)合法的file pointer 或者已經(jīng)被fclose關(guān)閉了的話。
那么在程序的第六行出,就會(huì)產(chǎn)生一個(gè)waring,并發(fā)生死循環(huán)。
為什么?
原因就是
Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.
所以,為了安全起見(jiàn),最好在使用上面代碼的時(shí)候 加個(gè)判斷,is_resource 還是比較安全的。
相關(guān)文章
PHP計(jì)算數(shù)組中值的和與乘積的方法(array_sum與array_product函數(shù))
這篇文章主要介紹了PHP計(jì)算數(shù)組中值的和與乘積的方法,結(jié)合實(shí)例形式較為詳細(xì)的分析了array_sum與array_product函數(shù)的功能與使用方法,需要的朋友可以參考下2016-04-04
PHP與Java對(duì)比學(xué)習(xí)日期時(shí)間函數(shù)
本文給大家介紹的是從Java和PHP進(jìn)行對(duì)比復(fù)習(xí)了下日期時(shí)間的處理函數(shù),并給出了一些示例,希望對(duì)大家能夠有所幫助2016-07-07
PHP 頁(yè)面跳轉(zhuǎn)到另一個(gè)頁(yè)面的多種方法方法總結(jié)
如何在PHP中從一個(gè)頁(yè)面重定向到另外一個(gè)頁(yè)面呢?這里列出了三種辦法,供參考。2009-07-07
PHP7.1實(shí)現(xiàn)的AES與RSA加密操作示例
這篇文章主要介紹了PHP7.1實(shí)現(xiàn)的AES與RSA加密操作,結(jié)合實(shí)例形式分析了php7.1環(huán)境下AES與RSA加密、解密操作相關(guān)實(shí)現(xiàn)與使用技巧,需要的朋友可以參考下2018-06-06

