php feof用来识别文件末尾字符的方法
作者:bea
EOF 是非常重要的概念,几乎每种主流编程语言都提供了相应的内置函数,来验证解析器是否到达了文件EOF。在PHP 中,此函数是feof ()。feof ()函数用来确定是否到达资源末尾。它在文件I/O 操作中经常使用。其形式为: int feof(string resource) 实例如下: 代码如下: <?php $fh = fopen("/home/www/data/users.txt", "rt"); while (!feof($fh)) echo fg
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 还是比较安全的。
有用 | 无用
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 还是比较安全的。
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- 为IP查询添加GOOGLE地图功能的代码
- PHP下对数组进行排序的函数
- PHP 冒泡排序算法的实现代码
- php下关于Cannot use a scalar value as an array的解决办法
- 在PHP中实现Javascript的escape()函数代码
- PHP下escape解码函数的实现方法
- ubuntu 编译安装php 5.3.3+memcache的方法
- PHP MemCached高级缓存配置图文教程
- PHP Array交叉表实现代码
- php垃圾代码优化操作代码
- PHP MemCached 高级缓存应用代码
- phpMyAdmin 链接表的附加功能尚未激活的问题
- PHP合并数组+与array_merge的区别分析
- PHP自定义函数收代码
- 无法在发生错误时创建会话,请检查 PHP 或网站服务器日志,并正确配置 PHP 安装最快的解决办法
- PHP5中使用PDO连接数据库的方法
- PHP网站安装程序制作的原理、步骤、注意事项和示例代码
- PHP Stream_*系列函数
- php下目前为目最全的CURL中文说明