名稱空間
變體
操作

std::filesystem::directory_entry::last_write_time

來自 cppreference.com
 
 
 
 
std::filesystem::file_time_type last_write_time() const;
(1) (C++17 起)
std::filesystem::file_time_type last_write_time( std::error_code& ec ) const noexcept;
(2) (C++17 起)

如果此 directory_entry 中快取了最後修改時間,則返回快取值。否則,返回

目錄

[編輯] 引數

ec - 非丟擲過載中用於錯誤報告的出參

[編輯] 返回值

所引用的檔案系統物件的最後修改時間。

[編輯] 異常

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

1) 在底層 OS API 錯誤時丟擲 std::filesystem::filesystem_error,其構造以 p 作為第一個路徑引數,OS 錯誤碼作為錯誤碼引數。
2) 如果 OS API 呼叫失敗,則將 std::error_code& 引數設定為 OS API 錯誤碼;如果沒有錯誤發生,則執行 ec.clear()

[編輯] 示例

#include <chrono>
#include <ctime>
#include <filesystem>
#include <format>
#include <iostream>
#include <string>
 
std::string to_string(const std::filesystem::file_time_type& ftime)
{
#if __cpp_lib_format
    return std::format("{:%c}", ftime);
#else
    std::time_t cftime = std::chrono::system_clock::to_time_t(
        std::chrono::file_clock::to_sys(ftime));
    std::string str = std::asctime(std::localtime(&cftime));
    str.pop_back(); // rm the trailing '\n' put by `asctime`
    return str;
#endif
}
 
int main()
{
    auto dir = std::filesystem::current_path();
    using Entry = std::filesystem::directory_entry;
    for (Entry const& entry : std::filesystem::directory_iterator(dir))
        std::cout << to_string(entry.last_write_time()) << " : "
                  << entry.path().filename() << '\n';
}

可能的輸出

Wed Sep  6 13:37:13.960314156 2023 : "main.cpp"
Wed Sep  6 13:37:42.690271828 2023 : "a.out"

[編輯] 參閱

獲取或設定最後資料修改時間
(函式) [編輯]