PHP 檔案系統 fdatasync() 函式



PHP 檔案系統 fdatasync() 函式用於將對檔案資料所做的更改與底層儲存裝置同步。但此函式與 fsync() 之間存在相似之處,僅同步檔案資料;不同步其元資料。

請記住,只有 POSIX(可移植作業系統介面)系統才能真正體現出此功能的不同之處。在 Windows 上,此函式是 fsync() 的別名。

語法

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

bool fdatasync(resource $stream)

引數

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

序號 引數和描述
1

$stream(必需)

檔案指標需要指向一個由 fopen() 成功開啟且未由 fclose() 關閉的檔案。它也需要是有效的。

返回值

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

PHP 版本

fdatasync() 函式首次引入於 PHP 8.1.0 版本。

示例

這是一個基本示例,用於演示如何使用 PHP 檔案系統 fdatasync() 函式來同步對檔案所做的更改。

<?php
   $filePointer = fopen('/PhpProjects/myfile.txt', 'w'); 
   fwrite($filePointer, 'Hello, world!'); 
   
   if (fdatasync($filePointer)) { 
      echo "File changes were saved successfully."; 
   } else { 
      echo "Could not save file changes."; 
   } 
   fclose($filePointer); 
?>

輸出

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

File changes were saved successfully.

示例

這是一個額外的 PHP 程式碼示例,演示了 fdatasync() 方法的使用。

<?php
   $fileHandle = fopen('/PhpProjects/sample.txt', 'w'); 
   fwrite($fileHandle, 'Hello, Tutorialspoint!'); 

   fdatasync($fileHandle); 
   fclose($fileHandle); 

   echo "File changes were saved successfully."; 
?> 

輸出

這將產生以下輸出:

File changes were saved successfully.

示例

這是一個使用 fdatasync() 函式同步提供的檔案內部資料的示例。

<?php
   $fileHandle = fopen('/PhpProjects/sample.txt', 'w'); 
   fwrite($fileHandle, "Line 1\n"); 
   fwrite($fileHandle, "Line 2\n"); 
   fwrite($fileHandle, "Line 3\n"); 

   fdatasync($fileHandle); 
   fclose($fileHandle); 

   echo "The sample changes were saved successfully."; 
?> 

輸出

這將生成以下輸出:

The sample changes were saved successfully.

示例

這是一個使用 fdatasync() 函式進行安全檔案建立的 fdatasync 示例。

<?php
   $data = "Name: Amit Sharma\nEmail: as@example.com\nMessage: Hello, this is a test message.";
   $fileHandle = fopen('/PhpProjects/sample.txt', 'w'); 
   fwrite($fileHandle, $data); 

   fdatasync($fileHandle); 
   fclose($fileHandle); 

   echo "The sample.txt file changes were saved successfully."; 
?> 

輸出

這將導致以下輸出:

以下是檔案資料:

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

以下是控制檯輸出:

The sample.txt file changes were saved successfully.

總結

fdatasync() 方法是一個內建函式,用於同步對檔案所做的更改,但它只同步檔案資料,不同步其元資料。該函式在成功時返回 true。

php_function_reference.htm
廣告