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



PHP 直接I/O dio_write() 函式用於將資料寫入檔案描述符,並可以選擇性地截斷長度。它是直接I/O函式的一部分,允許低階檔案訪問。

語法

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

int dio_write ( resource $fd , string $data [, int $len ] )

引數

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

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

  • $data: 要寫入的資料。

  • $len: 要寫入的位元組數。如果未給出,則將寫入完整的資料字串。

返回值

dio_write() 函式返回寫入的位元組數,或者在失敗時返回 FALSE。

PHP 版本

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

示例 1

這是 PHP 直接I/O dio_write() 函式的第一個基本示例,用於將簡單的字串寫入檔案。

<?php
   // Open a file for writing
   $fd = dio_open('/PHP/PhpProjects/myfile.txt', O_WRONLY | O_CREAT);
   
   // Write data to the file
   $data = "Hello, World!";
   
   $bytes_written = dio_write($fd, $data);
   
   // Close the file
   dio_close($fd);
   
   echo "Bytes written: " . $bytes_written;
?>

輸出

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

Bytes written: 13

示例 2

在此 PHP 示例程式碼中,我們將使用 dio_write() 函式,並僅將字串的一部分寫入檔案。

<?php
   // Open a file for writing
   $fd = dio_open('/PHP/PhpProjects/myfile.txt', O_WRONLY | O_CREAT);
   
   // Open a file for writing
   $fd = dio_open('example.txt', O_WRONLY | O_CREAT);
   
   // Write only the first 5 bytes of the string
   $data = "Hello, Tutorialspoint!";
   $bytes_written = dio_write($fd, $data, 5);
   
   // Close the file
   dio_close($fd);
   
   echo "Bytes written: " . $bytes_written;
?> 

輸出

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

Bytes written: 5

示例 3

現在,以下程式碼使用 dio_write() 將資料追加到給定的現有檔案中。

<?php
   // Open a file for appending
   $fd = dio_open('/PHP/PhpProjects/myfile.txt', O_WRONLY | O_APPEND);
   
   // Append data to the file
   $data = "\nThis is additional text.";
   $bytes_written = dio_write($fd, $data);
   
   // Close the file
   dio_close($fd);
   
   echo "Bytes written: " . $bytes_written;
?> 

輸出

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

Bytes written: 25

示例 4

在以下示例中,我們使用 dio_write() 函式透過迴圈將多個字串寫入檔案。

   <?php
   // Open a file for writing
   $fd = dio_open('/PHP/PhpProjects/myfile.txt', O_WRONLY | O_CREAT);
   
   // Write data to the file in a loop
   for ($i = 1; $i <= 5; $i++) {
       $data = "Line $i\n";
       dio_write($fd, $data);
   }
   
   // Close the file
   dio_close($fd);
   
   echo "Data written to file.";
   ?> 

輸出

這將建立以下輸出:

Data written to file.
php_function_reference.htm
廣告