命名空间
变体
操作

std::filesystem::last_write_time

来自 cppreference.cn
 
 
 
定义于头文件 <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 的公开成员函数) [编辑]