php feof函數用法與注意事項

來源:互聯網
上載者:User

php教程 feof函數用法與注意事項

eof() 函數檢測是否已到達檔案末尾 (eof)。
如果檔案指標到了 EOF 或者出錯時則返回 TRUE,否則返回一個錯誤(包括 socket 逾時),其它情況則返回 FALSE。
文法
feof(file)
參數 描述
file 必需。規定要檢查的開啟檔案。
說明
file 參數是一個檔案指標。這個檔案指標必須有效,並且必須指向一個由 fopen() 或 fsockopen() 成功開啟(但還沒有被 fclose() 關閉)的檔案。

<?php
$file = fopen("test.txt", "r");

//輸出文本中所有的行,直到檔案結束為止。
while(! feof($file))
  {
  echo fgets($file). "<br />";
  }

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)) {
事情原來是這樣子的:

<?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);
?>

提示和注釋
提示:feof() 函數對遍曆長度未知的資料很有用。
注意:如果伺服器沒有關閉由 fsockopen() 所開啟的串連,feof() 會一直等待直到逾時而返回 TRUE。預設的逾時限制是 60 秒,可以使用 stream_set_timeout() 來改變這個值。
注意:如果傳遞的檔案指標無效可能會陷入無限迴圈中,因為 EOF 不會返回 TRUE。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.