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

前端之家收集整理的这篇文章主要介绍了php feof用来识别文件末尾字符的方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

EOF 是非常重要的概念,几乎每种主流编程语言都提供了相应的内置函数,来验证解析器是否到达了文件EOF。在PHP 中,此函数是feof ()。feof ()函数用来确定是否到达资源末尾。它在文件I/O 操作中经常使用。其形式为: @H_4030@int feof(string resource) @H4030@实例如下: @H403_0@<div class="codetitle"><a style="CURSOR: pointer" data="21535" class="copybut" id="copybut21535" onclick="doCopy('code21535')"> 代码如下:

<div class="codebody" id="code21535"> @H_403_0@<?PHP @H_4030@$fh = fopen("/home/www/data/users.txt","rt"); @H4030@while (!feof($fh)) echo fgets($fh); @H4030@fclose($fh); @H4030@?> @H4030@
@H4030@bool feof ( resource $handle ):Tests for end-of-file on a file pointer @H403_0@这个PHP manual上面的原话。 @H_4030@为了方便,我以前都是这样使用的 @H403_0@<div class="codetitle"><a style="CURSOR: pointer" data="13249" class="copybut" id="copybut13249" onclick="doCopy('code13249')"> 代码如下:
<div class="codebody" id="code13249"> @H_403_0@<?PHP @H_4030@// if file can not be read or doesn't exist fopen function returns FALSE @H403_0@$file = @fopen("no_suchfile","r"); @H4030@// FALSE from fopen will issue warning and result in infinite loop here @H4030@while (!feof($file)) { @H4030@} @H4030@fclose($file); @H4030@?> @H4030@
@H403_0@确实,这样使用比较简单。但是,如果上面的变量$file不是一个合法的file pointer 或者已经被fclose关闭了的话。 @H_4030@那么在程序的第六行出,就会产生一个waring,并发生死循环。 @H4030@为什么? @H4030@原因就是 @H4030@Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE. @H403_0@所以,为了安全起见,最好在使用上面代码的时候 加个判断,is_resource 还是比较安全的。

猜你在找的PHP相关文章