当前位置: 移动技术网 > IT编程>开发语言>PHP > php feof用来识别文件末尾字符的方法

php feof用来识别文件末尾字符的方法

2019年04月28日  | 移动技术网IT编程  | 我要评论
eof 是非常重要的概念,几乎每种主流编程语言都提供了相应的内置函数,来验证解析器是否到达了文件eof。在php 中,此函数是feof ()。feof ()函数用来确定是否
eof 是非常重要的概念,几乎每种主流编程语言都提供了相应的内置函数,来验证解析器是否到达了文件eof。在php 中,此函数是feof ()。feof ()函数用来确定是否到达资源末尾。它在文件i/o 操作中经常使用。其形式为:
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 或者已经被fclose关闭了的话。
那么在程序的第六行出,就会产生一个waring,并发生死循环。
为什么?
原因就是
returns true if the file pointer is at eof or an error occurs (including socket timeout); otherwise returns false.
所以,为了安全起见,最好在使用上面代码的时候 加个判断,is_resource 还是比较安全的。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网