PHP 檔案系統 feof() 函式



PHP 檔案系統 feof() 函式用於判斷檔案是否已到達結尾。它代表“檔案結尾”。開啟檔案後,可以使用此函式來確定是否已完成讀取。如果發生錯誤或已到達檔案結尾 (EOF),此函式返回 true;否則返回 false。

feof() 函式對於遍歷長度未知的資料非常有用。如果您想從頭到尾讀取檔案,它會很有幫助。

語法

以下是 PHP 檔案系統 feof() 函式的語法:

bool feof ( resource $handle )

引數

使用 feof() 函式所需的的引數如下:

序號 引數和描述
1

handle(必需)

檔案指標需要指向一個由 fopen() 或 fsockopen() 成功開啟且未由 fclose() 關閉的有效檔案。

返回值

如果發生錯誤或檔案指標位於檔案末尾,則返回 TRUE,否則返回 FALSE。

PHP 版本

feof() 函式最初作為核心 PHP 4 的一部分引入,並與 PHP 5、PHP 7、PHP 8 良好相容。

示例

我們將建立一個 PHP 程式碼,其中我們以讀取模式開啟一個檔案,並使用 PHP 檔案系統 feof() 函式輸出開啟檔案的每一行,直到到達檔案末尾。

<?php
   $file = fopen("/PhpProject/sample.txt", "r");
   
   // Output a line of the file until the end is reached
   while(! feof($file)) {
      echo fgets($file);
   }
   fclose($file);
?>

輸出

這將產生以下結果:

tutorialspoint
tutorix

示例

在這個例子中,我們將讀取並顯示名為“image.jpg”的二進位制檔案的內容。我們將使用 rb 模式使用 fopen() 開啟檔案。

<?php
   // Open a file in binary mode
   $file = fopen("/Applications/XAMPP/xamppfiles/htdocs/mac/image.jpg", "rb"); 
   $file = fopen("image.jpg", "rb"); 

   // Output each byte of the file until it is reached at the end 
   while (!feof($file)) {
      
      // Read 1024 bytes at a time
      echo fread($file, 1024); 
   }
   fclose($file);
?> 

輸出

這將生成以下結果:

This will produce the content of "image.jpg" file if it is present in the directory.

示例

此 PHP 程式碼展示瞭如何開啟檔案以進行讀取,檢查檔案是否為空,然後關閉檔案。程式碼使用 feof() 函式檢查給定檔案是否為空。

<?php
   // Open a file for reading
   $file = fopen("/Applications/XAMPP/xamppfiles/htdocs/mac/data.csv", "r");

   // Check if the file is empty
   if (feof($file)) {
      echo "The file is empty.";
   } else {
      echo "The file is not empty.";
   }

   fclose($file);
?> 

輸出

這將建立以下結果:

The file is empty.

注意

  • 確保提供要讀取檔案的正確路徑。
  • 要正確處理檔案內容,請將 feof() 與讀取函式(如 fgets()、fread() 或 fgetc())一起使用。

總結

PHP 中的 feof() 函式是確定執行讀取操作時檔案結尾位置的有用工具。它可以用來檢查檔案是否為空,並且有助於確保檔案讀取迴圈正確結束。正確使用 feof() 可以使 PHP 程式碼中的檔案處理操作更安全。

php_function_reference.htm
廣告