std::filesystem::last_write_time是C++17引入的获取文件最后修改时间戳的函数,返回file_time_type类型值,需通过to_sys(C++20)或系统调用兜底转换为可读时间。
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(若编译器支持)。
-std=c++20 时支持 file_time_type::clock::to_sys
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 —— 这意味着:
tp.time_since_epoch().count() 在不同平台数值不可比to_sys() 转换就直接用 duration_cast 到 seconds 可能得负值(尤其 Windows 上)system_clock,导致 1970 年前时间显示异常如果目标环境不确定是否支持 to_sys,或需兼容 C++17 编译器,更稳妥的做法是绕过 std::filesystem,直接调用 POSIX stat 或 Windows GetFileTime:
struct stat st; stat(path.c_str(), &st); st.st_mtim.tv_sec
FILETIME ft; GetFileTime(hFile, nullptr, nullptr, &ft);,再用 FileTimeToSystemTime
boost::filesystem::last_write_time(返回 time_t)真正麻烦的从来不是“怎么取时间”,而是“怎么让这个时间在所有机器上都代表同一个时刻”。别迷信 std::filesystem 的跨平台承诺,尤其是涉及时间转换时,to_sys 是否可用、是否被正确实现,必须实测验证。