
std::filesystem::last_write_time 是什么函数
std::filesystem::last_write_time 是 C++17 引入的标准库函数,用于获取文件或目录的最后修改时间戳(std::filesystem::file_time_type 类型)。它不是“last_write_time_c++”——后者并不存在,属于常见拼写/记忆错误。
该函数返回的是一个高精度、与系统时钟对齐的时间点,但**不是 std::chrono::system_clock::time_point**,不能直接传给 std::put_time 或 std::format(C++20);需先转换。
如何正确获取并转换为可读时间字符串
直接调用 last_write_time 返回的是 file_time_type,而标准输出需要 system_clock::time_point。C++20 起可通过 std::filesystem::file_time_type::clock::to_sys 转换;C++17 需借助平台适配或第三方辅助(如 Boost),或使用 std::chrono::file_clock(若编译器支持)。
- Clang 14+/GCC 12+ 在启用
-std=c++20时支持file_time_type::clock::to_sys - MSVC 19.30+(VS 2022 17.0+)已实现该转换
- 若编译器不支持,
file_time_type无法安全转为system_clock,强行转换可能导致负偏移或崩溃
#include#include #include #include namespace fs = std::filesystem; int main() { auto fpath = fs::path("example.txt"); if (fs::exists(fpath)) { auto tp = fs::last_write_time(fpath); // C++20 推荐方式 auto sys_tp = fs::file_time_type::clock::to_sys(tp); auto tmc = std::chrono::system_clock::to_time_t(sys_tp); std::cout << std::put_time(std::localtime(&tmc), "%Y-%m-%d %H:%M:%S") << '\n'; } }
常见错误:跨平台时间戳解析失败
Windows 和 Linux 对 file_time_type 的底层实现不同:Windows 使用 FILETIME(100ns 单位,基于 1601 年),Linux 通常用 stat.st_mtim(纳秒级,基于 1970 年)。C++ 标准要求 file_time_type 表示“文件系统原生时间”,但未强制统一 epoch —— 这意味着:
立即学习“C++免费学习笔记(深入)”;
-
tp.time_since_epoch().count()在不同平台数值不可比 - 不做
to_sys()转换就直接用duration_cast到seconds可能得负值(尤其 Windows 上) - 某些旧版 libstdc++(GCC file_time_type 错误映射到
system_clock,导致 1970 年前时间显示异常
替代方案:用 stat 系统调用兜底(C++17 兼容)
如果目标环境不确定是否支持 to_sys,或需兼容 C++17 编译器,更稳妥的做法是绕过 std::filesystem,直接调用 POSIX stat 或 Windows GetFileTime:
- Linux/macOS:
struct stat st; stat(path.c_str(), &st); st.st_mtim.tv_sec - Windows:
FILETIME ft; GetFileTime(hFile, nullptr, nullptr, &ft);,再用FileTimeToSystemTime - 跨平台封装推荐用
boost::filesystem::last_write_time(返回time_t)
真正麻烦的从来不是“怎么取时间”,而是“怎么让这个时间在所有机器上都代表同一个时刻”。别迷信 std::filesystem 的跨平台承诺,尤其是涉及时间转换时,to_sys 是否可用、是否被正确实现,必须实测验证。









