自己曾写过这样一段代码:
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循环就退出了,为什么不是呢?
while (!feof($hd)) {
事情原来是这样子的:
<?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); ?>
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); ?>
<? $fp = fopen("myfile.txt", "r"); while(!feof($fp)) { $current_line = fgets($fp); if (!feof($fp)) { // process current line } } fclose($fp); ?>
<? $fp = fopen("myfile.txt", "r"); $current_line = fgets($fp); while (!feof($fp)) { // process current line $current_line = fgets($fp); } fclose($fp); ?>