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



PHP 直接I/O dio_read() 函式用於從檔案描述符讀取位元組。此函式可以從具有資源描述符的檔案中讀取並返回 len 個位元組。如果未指定 len,則 dio_read() 函式可以讀取 1K 塊並返回它。

語法

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

string dio_read(resource $fd, int $len = 1024)

引數

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

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

  • $len - 要讀取的位元組數(預設值為 1024 位元組)。

返回值

dio_read() 函式成功時返回讀取的字串,失敗時返回 FALSE。

PHP 版本

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

示例 1

此 PHP 示例程式碼演示瞭如何使用 PHP 直接I/O dio_read() 函式開啟檔案並讀取其內容。

<?php
   //open a file using dio_open
   $fd = dio_open('/PHP/PhpProjects/myfile.txt', O_RDONLY);

   //Read the file using dio_read
   $data = dio_read($fd, 256);

   // Close the file using dio_close
   dio_close($fd);

   echo $data;
?>

輸出

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

Hello, World!:
Line 1
Line 2
Line 3

示例 2

在下面的 PHP 程式碼中,我們將嘗試使用 dio_read() 函式從給定檔案中讀取 512 個位元組。

<?php
   // Open a file using dio_open
   $fd = dio_open('/PHP/PhpProjects/sample.txt', O_RDONLY);
   
   // Read 512 bytes
   $data = dio_read($fd, 512); 
   
   dio_close($fd);
   echo $data;
?> 

輸出

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

Name: Amit Sharma
Email: as@example.com
Message: Hello, this is a test message.

示例 3

現在,下面的程式碼使用 dio_read() 函式分塊讀取檔案,直到檔案結尾,並列印檔案內容。

<?php
   // Open a file using dio_open
   $fd = dio_open('/PHP/PhpProjects/newfile.txt', O_RDONLY);
   while ($data = dio_read($fd, 256)) {
       echo $data;
   }
   dio_close($fd);
?> 

輸出

這將建立以下輸出:

Hello this is a text file.

示例 4

在下面的示例中,我們使用 dio_read() 函式從序列埠讀取資料。

<?php
   // open a serial port
   $fd = dio_open('/dev/ttyS0', O_RDWR);

   // Read data
   $data = dio_read($fd, 128);
   dio_close($fd);
   echo $data;
?> 

輸出

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

Hello, this is data from the serial port.
php_function_reference.htm
廣告