c++17起可用std::filesystem::last_write_time获取文件修改时间,返回file_time_type类型时间点,windows为本地时区filetime(100ns),linux/macos基于stat.st_mtim(纳秒),跨平台比较安全。

用 std::filesystem::last_write_time 获取文件修改时间
标准 C++17 起,std::filesystem 提供了跨平台的文件时间访问能力。直接调用 std::filesystem::last_write_time(path) 可以拿到一个 std::filesystem::file_time_type 类型的时间点,它本质是高精度时钟(通常是纳秒级),但不保证与系统时钟或 wall clock 对齐。
注意:Windows 上返回的是本地时区下的 FILETIME(100ns 精度),Linux/macOS 通常基于 stat.st_mtim(纳秒精度),但比较操作本身是安全的——只要两个时间来自同一系统,、<code>== 运算符都可用。
示例:
namespace fs = std::filesystem;
auto t1 = fs::last_write_time("a.txt");
auto t2 = fs::last_write_time("b.txt");
if (t1
<h3>处理 <code>std::filesystem::file_time_type</code> 无法直接转 <code>time_t</code> 的问题</h3>
<p>你不能直接把 <code>file_time_type</code> 强转成 <code>time_t</code> 或塞进 <code>std::chrono::system_clock</code> ——它们的纪元(epoch)不同,强行转换会得到错误时间(比如 Windows 上可能显示为 1601 年)。除非你明确需要人类可读时间,否则**不要转**;直接比较原生类型最可靠。</p>
<p>如果真要转成秒级时间戳用于日志或调试(仅限开发期验证),需借助 <code>fs::file_time_type::clock</code> 的转换逻辑,但标准没强制要求支持转换到 <code>system_clock</code>。可行做法是:</p>
- 用
fs::file_time_type::time_since_epoch()拿到自该时钟 epoch 起的 duration - 但别试图除以 1s——因为 epoch 不同,数值无业务意义
- 真正需要可读时间时,改用
fs::last_write_time配合平台 API(如 Windows 的FileTimeToSystemTime,POSIX 的stat+localtime)
捕获异常并判断文件是否存在或不可访问
last_write_time 在文件不存在、权限不足或路径为 broken symlink 时会抛出 std::filesystem::filesystem_error。不加 try/catch 容易 crash。
常见错误信息包括:no such file or directory、Permission denied、Too many levels of symbolic links。
建议写法:
try {
auto t1 = fs::last_write_time("a.txt");
auto t2 = fs::last_write_time("b.txt");
return t1
<h3>Windows 下启用 <code>/std:c++17</code> 并链接 <code>Shlwapi.lib</code>
</h3>
<p>MSVC 默认不自动链接 <code>Shlwapi.lib</code>,而 <code>std::filesystem</code> 在 Windows 上依赖其中的 <code>PathCchCanonicalize</code> 等函数。不链接会导致链接错误,例如:<code>LNK2019: unresolved external symbol "class std::filesystem::path __cdecl std::filesystem::weakly_canonical</code>。</p>
<p>解决方式(任选其一):</p>
- 在项目属性 → 链接器 → 输入 → 附加依赖项中添加
Shlwapi.lib - 代码开头加
#pragma comment(lib, "Shlwapi.lib") - CMake 中添加
target_link_libraries(my_target PRIVATE Shlwapi)
另外确认编译选项已设为 /std:c++17 或更高;C++14 下 std::filesystem 不可用。
跨平台比较文件修改时间这件事,核心就两条:用对类型、别乱转时钟。最容易被忽略的是 Windows 下的链接依赖和异常边界——哪怕两个文件都存在,权限变化或符号链接环也能让程序当场退出。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!











