PHP - 直接I/O dio_seek() 函式



PHP 直接I/O dio_seek() 函式用於更改具有資源描述符的檔案中的位置。

語法

以下是 PHP 直接I/O dio_seek() 函式的語法:

int dio_seek (resource $fd, int $pos, int $whence = SEEK_SET)

引數

以下是 dio_seek() 函式的引數:

  • $fd − 由 dio_open() 返回的檔案描述符。

  • $pos − 要跳轉到的位置。

  • $whence − seek 操作的起始點。

$whence 引數

$whence 引數可以指定如何解釋 pos 位置:

  • SEEK_SET − pos 從檔案開頭指定。

  • SEEK_CUR − 指定 pos 是檔案當前位置的字元數,此數量可以是正數或負數。

  • SEEK_END − 指定 pos 是檔案末尾的字元數。負值可以指定當前檔案大小內的位置,正值可以指定檔案末尾後的位置。如果我們在當前檔案末尾之後設定一個位置並寫入資料,我們可以將檔案擴充套件到此位置。

返回值

dio_seek() 函式在成功時返回 0,失敗時返回 -1。

PHP 版本

dio_seek() 函式首次引入核心 PHP 4.2.0,在 PHP 5.1.0 中繼續輕鬆執行。

示例 1

此示例演示如何使用 PHP 直接I/O dio_seek() 函式將檔案指標移動到檔案開頭並讀取資料。

<?php
   // Mention file descriptor here 
   $fd = dio_open('/PHP/PhpProjects/newfile.txt', O_RDONLY);
   dio_seek($fd, 0, SEEK_SET);
   $data = dio_read($fd, 100);
   dio_close($fd);
   echo $data;
?>

輸出

以上程式碼將產生類似以下的結果:

Hello this is a text file.

示例 2

在下面的 PHP 程式碼中,我們將嘗試使用 dio_seek() 函式並從檔案讀取資料並將檔案指標移動到特定位置。檔案指標移動到檔案的第 50 個位元組,然後從該點開始讀取 50 個位元組。

<?php
   // Mention file descriptor here
   $fd = dio_open('/PHP/PhpProjects/sample.txt', O_RDONLY);
   dio_seek($fd, 50, SEEK_SET);
   $data = dio_read($fd, 50);
   echo $data;
   dio_close($fd);
?> 

輸出

執行上述程式後,它會生成以下輸出:

.com
Message: Hello, this is a test message.

示例 3

此示例將使用 dio_seek() 函式,以便可以將檔案指標移動到檔案末尾。

<?php
   // Mention file descriptor here
   $fd = dio_open('/PHP/PhpProjects/myfile.txt', O_RDONLY);
   dio_seek($fd, 0, SEEK_END);
   echo "Pointer moved to the end of the file.";
   dio_close($fd);
?> 

輸出

這將建立以下輸出:

Pointer moved to the end of the file.

示例 4

此示例顯示瞭如何在 dio_seek() 函式的幫助下相對於其當前位置重新定位檔案指標。

<?php
   // Mention file descriptor here
   $fd = dio_open('/PHP/PhpProjects/newfile.txt', O_RDONLY);
   dio_seek($fd, 10, SEEK_CUR);
   $data = dio_read($fd, 50);
   dio_close($fd);
   echo $data;
?> 

輸出

執行上述程式時,將產生以下輸出:

 is a text file.
php_function_reference.htm
廣告