當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


PHP feof( )用法及代碼示例

PHP中的feof()函數是一個內置函數,用於測試文件指針上的文件結尾。它檢查是否已到達文件末尾。如果內容大小事先未知,則feof()函數用於循環瀏覽文件的內容。

如果已到達文件末尾或發生錯誤,則feof()函數將返回True。否則返回False。

用法:


feof( $file )

參數:PHP中的feof()函數僅接受一個參數$file。此參數指定必須檢查文件結尾的文件。

返回值:如果已到達文件末尾或發生錯誤,則返回TRUE。否則返回False。

錯誤與異常

  1. 如果傳遞的文件指針無效,則會進入無限循環,因為文件末尾無法返回True。
  2. 如果服務器未關閉由fsockopen()打開的連接,則feof()函數將掛起。

以下示例程序旨在說明feof()函數:

程序1::在下麵的程序中,名為“singleline.txt”的文件僅包含一行文本,即“此文件僅包含一行。”。

<?php 
  
// a file is opened using fopen() function 
$check = fopen("singleline.txt", "r"); 
  
$seq = fgets($check); 
  
// Outputs a line of the file until 
// the end-of-file is reached 
while(! feof($check)) 
{ 
  echo $seq ; 
  $seq = fgets($check); 
} 
  
// file is closed using fclose() function 
fclose($check); 
  
?>

輸出:

This file consists of only a single line.

程序2:注意:在下麵的程序中,名為“gfg.txt”的文件包含以下文本。

This is the first line.
This is the second line.
This is the third line.

<?php 
  
// a file is opened using fopen() function 
$check = fopen("gfg.txt", "r"); 
$seq = fgets($check); 
  
// Outputs a line of the file until 
// the end-of-file is reached 
while(! feof($check)) 
{ 
  echo $seq ; 
  $seq = fgets($check); 
} 
  
// file is closed using fclose() function 
fclose($check); 
  
?>

輸出:

This is the first line.
This is the second line.
This is the third line.

參考:
http://php.net/manual/en/function.feof.php



相關用法


注:本文由純淨天空篩選整理自Shubrodeep Banerjee大神的英文原創作品 PHP | feof() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。