std::filesystem::last_write_time是C++17标准方式,返回file_time_type类型,需经to_time_t转换后再用localtime和put_time格式化;必须传绝对路径并验证存在性,否则抛filesystem_error。

用 std::filesystem::last_write_time 获取可执行文件修改时间
直接调用 std::filesystem::last_write_time 是最标准的做法,但它返回的是 std::filesystem::file_time_type,不是秒数或字符串,不能直接打印。你需要先转成系统时钟时间再格式化。
关键点:必须传入可执行文件的绝对路径,不能只传 "./" 或空字符串;否则会抛出 std::filesystem::filesystem_error。
- 用
std::filesystem::canonical(std::filesystem::current_path() / argv[0])获取真实路径(注意:argv[0]可能是相对路径或不含目录) - Windows 下若
argv[0]不含反斜杠,current_path() / argv[0]可能拼错;推荐改用GetModuleFileName(Windows)或/proc/self/exe(Linux)补救 -
last_write_time返回的时间精度依赖底层文件系统(如 FAT32 是 2 秒,NTFS 是 100ns)
跨平台获取可执行文件路径的稳妥写法
仅靠 argv[0] 在 shell 调用、符号链接、PATH 查找等场景下不可靠。必须做路径规范化 + 存在性验证。
Linux 示例(使用 /proc/self/exe):
立即学习“C++免费学习笔记(深入)”;
std::filesystem::path exe_path;
#ifdef __linux__
char buf[PATH_MAX];
ssize_t len = readlink("/proc/self/exe", buf, sizeof(buf)-1);
if (len > 0) {
buf[len] = '\0';
exe_path = std::filesystem::path(buf);
}
#endif
Windows 示例(使用 GetModuleFileNameW):
#ifdef _WIN32
wchar_t buf[MAX_PATH];
if (GetModuleFileNameW(nullptr, buf, MAX_PATH) > 0) {
exe_path = std::filesystem::path(buf);
}
#endif
- 无论哪种方式,拿到路径后务必用
std::filesystem::exists(exe_path)检查,防止符号链接失效或权限不足 - 不要对
exe_path直接调用last_write_time前跳过is_regular_file判断——软链接本身没有修改时间,需follow_symlink或先canonical
file_time_type 转本地时间字符串的常见坑
std::filesystem::file_time_type 和 std::chrono::system_clock::time_point 类型不兼容,不能直接强转。C++20 提供了 clock_cast,但很多编译器(如 GCC 12/Clang 14)尚未完全支持。
- 稳妥做法:用
std::filesystem::file_time_type::clock::to_time_t(如果该 clock 支持),但注意file_time_type::clock在不同平台可能不同(libstdc++ 用system_clock,MSVC 用自定义 clock) - 更通用方案:用
std::chrono::duration_cast<:chrono::seconds>(tp.time_since_epoch()).count()</:chrono::seconds>提取秒数,再用std::localtime格式化(丢失亚秒精度,但够用) - 别用
std::put_time直接格式化file_time_type—— 编译失败且错误信息晦涩(例如 “no matching function for call to ‘to_stream’”)
编译与运行时依赖检查
std::filesystem 不是“开箱即用”的。即使写了 #include <filesystem>,仍可能链接失败或运行时报错。
- g++ 需显式加
-lstdc++fs(GCC -lc++fs;CMake 中要写target_link_libraries(myapp PRIVATE stdc++fs) - Windows MSVC 默认启用,但若项目设置为 /clr 或 /ZW,可能禁用 filesystem;检查是否定义了
_HAS_FILESYSTEM=1 - 运行时若提示
undefined symbol: _ZNSt10filesystem7__cxx114pathD1Ev,基本是链接参数漏了或 ABI 不匹配(比如混用了 libstdc++ 和 libc++)
时间精度、路径可靠性、类型转换、链接配置——这四个点只要漏掉一个,last_write_time 就会静默失败或崩溃。尤其注意 argv[0] 不等于可执行文件路径这件事,很多人卡在这里一整天。


















