eof() 函数检测是否已到达文件末尾(eof).
如果文件指针到了 EOF 或者出错时则返回 TRUE,否则返回一个错误(包括 socket 超时),其它情况则返回 FALSE.
语法:feof(file)
参数 描述
file 必需,规定要检查的打开文件.
说明:file 参数是一个文件指针,这个文件指针必须有效,并且必须指向一个由 fopen() 或 fsockopen() 成功打开(但还没有被 fclose() 关闭)的文件.
$file=fopen("test.txt","r");
//输出文本中所有的行,直到文件结束为止。
while(!feof($file))
{
echofgets($file)."
";
}
fclose($file);
?>
if(file_exists($pmr_config["datasetfile"])){
$tmp_counter= 0;
$hd=fopen($pmr_config["datasetfile"],"r");
if($hd!== FALSE){
while(!feof($hd)) {
$buffer=fgets($hd);
if($tmp_counter>=$seq){
$result[] =$buffer;
}
$tmp_counter++;
if($tmp_counter>=$seq+$size){
break;
}
}
}else{
echo"warning:open file {$pmr_config["datasetfile"]} failed!PHP_EOL";
}
}else{
echo"warning:file {$pmr_config["datasetfile"]} does not exsits!PHP_EOL";
}
其中当读取行数包括文件结尾的时候,$result数组中总会比期望的内容多出来一个元素:
(boolean)false
按说,如果读取到最后一行,feof函数会返回TRUE,然后while循环就退出了,为什么不是呢?
1
while (!feof($hd)) {
事情原来是这样子的:
// 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);
?>
feof() is, in fact, reliable. However, you have to use it carefully in conjunction with fgets(). A common (but incorrect) approach is to try something like this:
$fp=fopen("myfile.txt","r");
while(!feof($fp)) {
$current_line=fgets($fp);
// do stuff to the current line here
}
fclose($fp);
?>
提示和注释:
提示:feof() 函数对遍历长度未知的数据很有用。
注意:如果服务器没有关闭由 fsockopen() 所打开的连接,feof() 会一直等待直到超时而返回 TRUE,默认的超时限制是 60 秒,可以使用 stream_set_timeout() 来改变这个值.
注意:如果传递的文件指针无效可能会陷入无限循环中,因为 EOF 不会返回 TRUE.
(责任编辑:admin)