名稱空間
變體
操作

std::filesystem::last_write_time

來自 cppreference.com
 
 
 
定義於標頭檔案 <filesystem>
(1) (C++17 起)
std::filesystem::file_time_type last_write_time( const std::filesystem::path& p,
                                                 std::error_code& ec ) noexcept;
(2) (C++17 起)
void last_write_time( const std::filesystem::path& p,
                      std::filesystem::file_time_type new_time );
(3) (C++17 起)
void last_write_time( const std::filesystem::path& p,

                      std::filesystem::file_time_type new_time,

                      std::error_code& ec ) noexcept;
(4) (C++17 起)
1,2) 返回 p 最後修改時間,其確定方式如同訪問 POSIX stat 的成員 st_mtime(符號連結被跟隨)。無丟擲異常過載在錯誤時返回 file_time_type::min()
3,4) 更改 p 的最後修改時間,如同透過 POSIX futimens(符號連結被跟隨)。

目錄

[編輯] 引數

p - 要檢查或修改的路徑
new_time - 新的修改時間
ec - 非丟擲過載中用於錯誤報告的出參

[編輯] 返回值

1,2) p 的最後修改時間。
3,4) (無)

[編輯] 異常

任何未標記為 noexcept 的過載都可能在記憶體分配失敗時丟擲 std::bad_alloc

1,3) 當底層 OS API 發生錯誤時丟擲 std::filesystem::filesystem_error,其構造時以 p 為第一路徑引數,以 OS 錯誤碼為錯誤碼引數。
2,4) 若 OS API 呼叫失敗,則設定 std::error_code& 引數為 OS API 錯誤碼;若無錯誤發生,則執行 ec.clear()

[編輯] 註記

不保證在設定寫時間後,(1,2) 返回的值與傳遞給 (3,4) 的引數相同,因為檔案系統的時間粒度可能比 filesystem::file_time_type 更粗。

[編輯] 示例

#include <chrono>
#include <filesystem>
#include <format>
#include <fstream>
#include <iostream>
 
using namespace std::chrono_literals;
 
int main()
{
    auto p = std::filesystem::temp_directory_path() / "example.bin";
    std::ofstream{p.c_str()}.put('a'); // create file
 
    std::filesystem::file_time_type ftime = std::filesystem::last_write_time(p);
    std::cout << std::format("File write time is {}\n", ftime);
 
    // move file write time 1 hour to the future
    std::filesystem::last_write_time(p, ftime + 1h);
 
    // read back from the filesystem
    ftime = std::filesystem::last_write_time(p);
    std::cout << std::format("File write time is {}\n", ftime);
 
    std::filesystem::remove(p);
}

可能的輸出

File write time is 2023-09-04 19:33:24.702639224
File write time is 2023-09-04 20:33:24.702639224

[編輯] 參閱

表示檔案時間值
(typedef) [編輯]
獲取目錄項所引用檔案的上次資料修改時間
(std::filesystem::directory_entry 的公開成員函式) [編輯]