PHP 檔案系統 rewind() 函式



PHP 檔案系統 rewind() 函式用於將檔案指標的位置倒回到檔案的開頭,如果成功則返回 true,失敗則返回 false。

此函式可以將控制代碼的檔案位置指示器設定為檔案流的開頭。如果我們以追加 ("a" 或 "a+") 模式打開了一個檔案,那麼我們寫入檔案的所有資料都始終會被追加,而不管檔案指標的位置如何。

語法

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

bool rewind ( resource $handle )

引數

以下是 rewind() 函式唯一必需的引數:

序號 引數和描述
1

$handle(必需)

它是檔案指標,它應該是有效的,並且指向由 fopen() 成功開啟的檔案。

返回值

rewind() 函式在成功時返回 TRUE,失敗時返回 FALSE。

PHP 版本

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

示例

這是一個基本示例,展示瞭如何使用 PHP 檔案系統 rewind() 函式來倒回檔案指標的位置。

<?php
   $handle = fopen("/PhpProjects/sample.txt", "r+");

   fwrite($handle, "Long sentence");
   rewind($handle);
   fwrite($handle, "Hello PHP");
   rewind($handle);

   echo fread($handle, filesize("/PhpProject/sample.txt"));
   fclose($handle);
?>

輸出

以下是以下程式碼的結果:

Hello PHPence

示例

在另一個示例中,我們將向您展示如何將 rewind() 和 fseek() 函式結合使用來處理檔案。

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

   fseek($file, "15");  // Change the position of file pointer
   rewind($file);  // Set the file pointer to 0

   fclose($file);
?> 

輸出

這將產生以下結果:

# No output of this code

示例

再舉一個例子,讀取檔案並列印內容,在再次列印資料後,將指標移回檔案的開頭。

<?php
   // Open file for reading
   $file = fopen("/PhpProjects/myfile.txt", "r"); 

   // Read data from the file
   $data = fgets($file);
   echo $data; // Output the first line of data

   rewind($file); // Move pointer back to the beginning of the file

   // Read data again from the beginning
   $data = fgets($file);
   echo $data; // Output the first line of data again

   fclose($file);
?> 

輸出

這將生成以下輸出:

Hello this is a text file.
Hello this is a text file.

示例

此示例演示瞭如何使用 rewind() 重置檔案指標。即使您已經讀取了部分檔案,它也允許您再次從檔案的開頭讀取。

<?php
   // Open file for reading
   $file = fopen("/PhpProjects/myfile.txt", "r+"); 

   // Read the first line of the file
   $line1 = fgets($file);
   echo "First line: " . $line1 . "\n";

   // Read the second line of the file
   $line2 = fgets($file);
   echo "Second line: " . $line2 . "\n";

   // Move the file pointer back to the starting point of the file
   rewind($file);

   // Read the first line again after rewinding
   $rewindedLine = fgets($file);
   echo "First line after rewind: " . $rewindedLine . "\n";

   fclose($file); // Close the file
?> 

輸出

這將導致以下輸出:

First line: Hello this is a text file.

Second line: Tutorialspoint is a great website for learners.

First line after rewind: Hello this is a text file.

總結

rewind() 方法是一個內建函式,用於倒回給定檔案的檔案指標。如果您想再次從開頭讀取檔案或在之前讀取或寫入檔案後必須從頭開始寫入,這非常重要。

php_function_reference.htm
廣告