Namespaces
Variants

std::experimental::filesystem:: last_write_time

From cppreference.net
定义于头文件 <experimental/filesystem>
file_time_type last_write_time ( const path & p ) ;
file_time_type last_write_time ( const path & p, error_code & ec )
(1) (filesystem TS)
void last_write_time ( const path & p, file_time_type new_time ) ;
void last_write_time ( const path & p, file_time_type new_time, error_code & ec ) ;
(2) (filesystem TS)
1) 返回 p 的最后修改时间,该时间通过访问 POSIX stat st_mtime 成员确定(遵循符号链接)。 非抛出重载在出错时返回 file_time_type :: min ( )
2) 修改 p 的最后修改时间,如同通过 POSIX futimens 实现(符号链接会被跟踪)。

目录

参数

p - 要检查或修改的路径
new_time - 新的修改时间
ec - 非抛出重载中用于错误报告的输出参数

返回值

1) p 的最后修改时间。
2) (无)

异常

The overload that does not take an error_code & parameter throws filesystem_error on underlying OS API errors, constructed with p as the first argument and the OS error code as the error code argument. std:: bad_alloc may be thrown if memory allocation fails. The overload taking an error_code & parameter sets it to the OS API error code if an OS API call fails, and executes ec. clear ( ) if no errors occur. This overload has
noexcept 规范:
noexcept

注释

不能保证在设置写入时间后, (1) 的返回值会立即等同于传递给 (2) 的参数值,因为文件系统的时间精度可能比 file_time_type 更精细。

示例

#include <chrono>
#include <experimental/filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
namespace fs = std::experimental::filesystem;
using namespace std::chrono_literals;
int main()
{
    fs::path p = fs::current_path() / "example.bin";
    std::ofstream(p.c_str()).put('a'); // 创建文件
    auto ftime = fs::last_write_time(p);
    std::time_t cftime = decltype(ftime)::clock::to_time_t(ftime); // 假设为系统时钟
    std::cout << "文件写入时间为 " << std::asctime(std::localtime(&cftime)) << '\n';
    fs::last_write_time(p, ftime + 1h); // 将文件写入时间向后移动1小时
    ftime = fs::last_write_time(p); // 从文件系统重新读取
    cftime = decltype(ftime)::clock::to_time_t(ftime);
    std::cout << "文件写入时间为 " << std::asctime(std::localtime(&cftime)) << '\n';
    fs::remove(p);
}

可能的输出:

文件写入时间为 Tue Mar 31 19:47:04 2015
文件写入时间为 Tue Mar 31 20:47:04 2015

参见

表示文件时间值
(类型定义)