PHP 檔案系統 ftell() 函式



PHP 檔案系統ftell()函式用於返回開啟檔案中當前的位置,這意味著它在檔案流中的偏移量。它可以在成功時返回當前檔案指標位置,或者在失敗時返回 false。

語法

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

int ftell ( resource $handle )

引數

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

序號 引數及描述
1

handle(必填)

指向開啟檔案的的檔案指標資源。

返回值

它在成功時返回一個包含檔案指標當前位置的整數,或者在失敗時返回 FALSE。

PHP 版本

ftell()函式最初作為核心 PHP 4 的一部分引入,並且可以很好地與 PHP 5、PHP 7、PHP 8 一起使用。

示例

這是一個基本的示例,它展示瞭如何使用 PHP 檔案系統ftell()函式。因此它開啟一個檔案進行讀取,然後列印檔案指標的當前位置。

<?php
   // Open the file using file path 
   $file = fopen("/Path/To/The/File", "r");

   // print current position
   echo ftell($file);
?>

輸出

以下是上述示例的輸出:

0

示例

此 PHP 程式碼在使用ftell()函式讀取檔案後修改了檔案內部的讀取位置。

<?php
   $file = fopen("/PhpProject/sample.txt", "r");

   // print current position
   echo ftell($file);

   // change current position
   fseek($file, "10");

   // print current position again
   echo "\n" . ftell($file);

   fclose($file);
?>

輸出

以下是輸出:

0
10

示例

此 PHP 程式碼建立一個新檔案,從中讀取一行,列印檔案指標的當前位置,然後關閉它。

<?php
   // opens a file and read data
   $file = fopen("/PhpProject/sample.txt", "r");
   $data = fgets($file, 7);

   echo ftell($file); 
   fclose($file);
?>

輸出

以上程式碼產生以下結果:

6

示例

此 PHP 程式碼從給定檔案中讀取多行,並使用ftell()函式在讀取每一行後列印檔案指標的位置。

<?php
   // Opens a file in read mode
   $file = fopen("/PhpProject/sample.txt", "r");

   if ($file) {
      while (!feof($file)) {
         // Read a line from the file
         $line = fgets($file);
         
         // Display the current position of the file pointer
         echo "Position after reading line: " . ftell($file) . "\n";
      }
      fclose($file);

   } else {
      echo "Unable to open the file.";
   }
?> 

輸出

這將產生以下結果:

Position after reading line: 14

示例

在此 PHP 程式碼中,我們將使用 fseek() 將檔案指標移動到檔案的末尾,並使用ftell()函式顯示檔案大小。

<?php
   // Opens a file in read mode
   $file = fopen("/PhpProject/sample.txt", "r");

   if ($file) {
      // Move the file pointer to the end of the file
      fseek($file, 0, SEEK_END);
      
      // Display the position of the file pointer (file size)
      echo "File size: " . ftell($file) . "bytes";
      
      // Close the file
      fclose($file);
   } else {
      echo "Unable to open the file.";
   }
?> 

輸出

這將生成以下輸出:

File size: 104 bytes

注意

由於 PHP 的整數型別是有符號的,並且許多平臺使用 32 位整數,因此對於大於 2GB 的檔案,多個檔案系統方法可能會產生意外的結果。

總結

使用 PHP 的ftell()函式查詢開啟檔案中檔案指標的當前位置。當您需要跟蹤已讀取的檔案量或在檔案內部的特定區域執行操作時,此函式非常有用。

php_function_reference.htm
廣告