php feof用來識別文件末尾字符的方法
更新時間:2010年08月01日 19:12:04 作者:
程序需要一種標(biāo)準(zhǔn)的方式來識別何時到達(dá)文件的末尾.這個標(biāo)準(zhǔn)通常稱為文件末尾,或EOF字符。
EOF 是非常重要的概念,幾乎每種主流編程語言都提供了相應(yīng)的內(nèi)置函數(shù),來驗證解析器是否到達(dá)了文件EOF。在PHP 中,此函數(shù)是feof ()。feof ()函數(shù)用來確定是否到達(dá)資源末尾。它在文件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)文章
jQuery中的RadioButton,input,CheckBox取值賦值實現(xiàn)代碼
本篇文章主要是對jQuery中的RadioButton,input,CheckBox取值賦值實現(xiàn)代碼進(jìn)行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-02-02驗證token、回復(fù)圖文\文本、推送消息的實用微信類php代碼
這篇文章主要為大家詳細(xì)介紹了php代碼實現(xiàn)驗證token、回復(fù)圖文\文本、推送消息的實用微信類,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-06-06php include,include_once,require,require_once
其實PHP包含文件的這四個函數(shù),很多人還是沒完全明白的,雖然用的時候多,但是具體某些地方該怎么用,用那一個,我就獻(xiàn)丑一把.2008-09-09學(xué)習(xí)php設(shè)計模式 php實現(xiàn)模板方法模式
這篇文章主要介紹了php設(shè)計模式中的模板方法模式,使用php實現(xiàn)模板方法模式,感興趣的小伙伴們可以參考一下2015-12-12PHP中功能強(qiáng)大卻很少使用的函數(shù)實例小結(jié)
這篇文章主要介紹了PHP中功能強(qiáng)大卻很少使用的函數(shù),結(jié)合實例形式總結(jié)分析了php中非常實用的幾個函數(shù),包括函數(shù)的調(diào)用、注冊、調(diào)用、判斷等操作技巧,需要的朋友可以參考下2016-11-11使用zend studio for eclipse不能激活代碼提示功能的解決辦法
相信有蠻多人用zend studio for eclipse寫代碼吧,但有時候好好的一個項目就突然沒得語法提示,很郁悶。2009-10-10