能,std::filesystem::last_write_time可直接修改文件最后写入时间,但要求路径合法、文件可写且不跨文件系统;需使用fs::file_time_type类型时间点,转换time_t时须经system_clock中转并用time_point_cast避免精度丢失。

std::filesystem::last_write_time能直接修改文件时间吗
能,但需要目标文件可写且路径合法。它不支持跨文件系统操作,也不能修改只读文件的最后写入时间——此时会抛出 std::filesystem::filesystem_error,错误码通常是 permission_denied。
常见错误现象:terminate called after throwing an instance of 'std::filesystem::filesystem_error',往往是因为权限不足或路径不存在。
- 确保路径存在且是普通文件(非目录、符号链接)
- Windows 下需有写权限;Linux/macOS 下需对文件有写权限(不一定要对父目录有写权限)
- 不能用它修改挂载为只读的文件系统上的文件
修改 last_write_time 的基本写法(C++17+)
调用 std::filesystem::last_write_time 传入路径和新的时间点即可。时间点类型必须是 std::filesystem::file_time_type,不是 std::chrono::system_clock::time_point 或 std::time_t —— 这是初学者最常踩的类型转换坑。
示例:将文件时间设为当前时间
#include <filesystem>
#include <chrono>
namespace fs = std::filesystem;
fs::path p{"example.txt"};
fs::last_write_time(p, fs::file_time_type::clock::now());
</chrono></filesystem>
注意:fs::file_time_type::clock::now() 是正确获取当前文件系统时间的方式;用 std::chrono::system_clock::now() 直接传入会编译失败。
如何把 time_t 或 struct tm 转成 file_time_type
标准库没提供直接转换函数,得手动桥接。核心是通过 std::chrono::system_clock 中转,再用 fs::clock 的时钟转换(因为两者不一定等价)。
- 从
time_t转换:先转成system_clock::time_point,再用std::chrono::time_point_cast转到fs::file_time_type - Windows 上
fs::file_time_type通常基于FILETIME(100ns 精度),Linux/macOS 基于stat::st_mtim(纳秒级),所以高精度时间可能被截断 - 不要用
std::chrono::duration_cast强转,容易因精度丢失导致时间偏移几秒
安全转换示例:
time_t t = std::time(nullptr); auto tp = std::chrono::system_clock::from_time_t(t); auto ft = std::chrono::time_point_cast<:file_time_type::duration>(tp); fs::last_write_time(p, ft); </:file_time_type::duration>
修改时间后是否立即生效?有没有缓存问题
调用成功即写入操作系统,无用户态缓存。但要注意:
- 某些文件系统(如 NFS、FAT32)可能不支持纳秒级精度,实际保存时会被向下取整到 2 秒或 10ms 级别
- Windows 上如果启用了“最后访问时间更新”优化(默认开启),
last_write_time不会影响last_access_time,但反过来不会触发写时间更新 - 修改后立刻用
fs::last_write_time(p)读取,结果应与写入值一致;若不一致,说明文件系统不支持该精度或权限异常
真正容易被忽略的是时区处理:file_time_type 是 UTC 时间,所有转换都应在 UTC 上进行,不要用本地时区的 struct tm 直接构造 —— 否则在夏令时切换日附近可能偏差一小时。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!











