命名空间
变体
操作

std::filesystem::directory_entry::last_write_time

来自 cppreference.cn
 
 
 
 
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"

[编辑] 参阅

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