Namespaces
Variants

std::filesystem::directory_entry:: last_write_time

From cppreference.net
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) 当底层操作系统 API 出错时抛出 std::filesystem::filesystem_error ,其中以 p 作为第一个路径参数,操作系统错误代码作为错误码参数进行构造。
2) 若操作系统API调用失败,将 std:: error_code & 参数设置为操作系统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(); // 移除 `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"

参见

获取或设置最后数据修改时间
(函数)