PHP 中的feof方法

bool feof ( resource $handle ):Tests for end-of-file on a file pointer
 
这个php manual上面的原话。
为了方便,我以前都是这样使用的
1 <?php
2  // if file can not be read or doesn't exist fopen function returns FALSE
3  $file = @fopen("no_such_file", "r");
4
5 // FALSE from fopen will issue warning and result in infinite loop here
6 while (!feof($file)) {
7 }
8
9 fclose($file);
10 ?>

确实,这样使用比较简单。但是,如果上面的变量$file不是一个合法的file pointer 或者已经被fclose关闭了的话。

那么在程序的第六行出,就会产生一个waring,并发生死循环。

为什么?

原因就是

Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.

所以,为了安全起见,最好在使用上面代码的时候 加个判断,is_resource 还是比较安全的。

 

 

原文地址:https://www.cnblogs.com/ainiaa/p/1789709.html