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



PHP 直接I/O dio_truncate() 函式用於截斷(縮短)檔案到給定長度。這意味著如果內容在設定時間後被移除,檔案可能會變小。

語法

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

bool dio_truncate (resource $fd, int $length)

引數

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

  • $fd - 這是一個資源,通常使用 dio_open() 獲取。

  • $length - 這是檔案應截斷到的長度。這是一個整數。

返回值

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

PHP 版本

dio_truncate() 函式首次引入於 PHP 4.3.0 的核心 PHP 中,並在 PHP 5.1.0 中繼續輕鬆執行。

示例 1

首先,我們將向您展示 PHP 直接I/O dio_truncate() 函式開啟檔案並將其截斷為 10 位元組的基本示例。

<?php
   // Open a file descriptor
   $fd = dio_open('/PHP/PhpProjects/myfile.txt', O_RDWR);
   if ($fd) {
       dio_truncate($fd, 10);
       dio_close($fd);
   }
   echo "The file is truncated successfully!";
?>

輸出

以上程式碼將產生類似於這樣的結果:

The file is truncated successfully!

示例 2

在下面的 PHP 程式碼中,我們將嘗試使用 dio_truncate() 函式,並將檔案截斷為零位元組以清空它。

<?php
   // Open a file descriptor
   $fd = dio_open('/PHP/PhpProjects/sample.txt', O_RDWR);
   if ($fd) {
       dio_truncate($fd, 0);
       dio_close($fd);
   }
   
   echo "Truncated a File to Zero Bytes";
?> 

輸出

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

Truncated a File to Zero Bytes

示例 3

現在,下面的程式碼使用 dio_truncate() 函式處理截斷檔案時的錯誤,並列印錯誤訊息。

<?php
   // Open a file descriptor
   $fd = dio_open('/PHP/PhpProjects/newfile.txt', O_RDWR);
   if ($fd) {
       if (!dio_truncate($fd, 10)) {
           echo "Error truncating file";
       }
       dio_close($fd);
   } else {
       echo "Error opening file";
   }
?> 

輸出

這將建立以下輸出:

Error truncating file
php_function_reference.htm
廣告