PHP feof测试文件指针是否到了文件结束的位置
Jun 13, 2016 am 10:40 AM
EOF 是非常重要的概念,几乎每种主流编程语言都提供了相应的内置函数,来验证解析器是否到达了文件EOF。在PHP 中,此函数是feof ()。feof ()函数用来确定是否到达资源末尾。它在文件I/O 操作中经常使用。其形式为:
int feof(string resource)
实例代码如下:
$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上面的原话。
为了方便,我以前都是这样使用的
// if file can not be read or doesnt 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 还是比较安全的

인기 기사

인기 기사

뜨거운 기사 태그

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드

PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법
