std::filesystem::last_write_time是否要求最低Windows 10版本?
std::filesystem::last_write_time 在旧版Windows系统中抛出异常的问题
最简复现代码
#include <fstream> #include <iostream> #include <filesystem> int main() { auto last_write_time = std::filesystem::temp_directory_path() / "last_write_time.txt"; std::ofstream(last_write_time.c_str()) << "Hello, World!"; try { auto ftime = std::filesystem::last_write_time(last_write_time); std::cout << ftime << std::endl; } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } std::filesystem::remove(last_write_time); }
测试结果
- Windows 10 Enterprise 2016 LTSB Version 1607:抛出异常,信息为"unknown error"
- 同版本另一台机器:抛出异常,信息为"The specified module could not be found."
- Windows 7 Embedded Standard 6.1.7601 Service Pack 1 Build 7601:抛出异常,信息为"The specified module could not be found."
- Windows 10 Pro Version 22H2:可正常运行
- Windows 11 Enterprise Version 23H2:可正常运行
原因说明
根据微软STL的VS2019 16.10版本更新内容,std::filesystem::last_write_time与std::chrono::current_zone类似,对Windows系统版本有最低要求——仅支持Windows 10及以上版本。旧版Windows系统(如Windows 7、Windows 10 1607 LTSB)缺少该API底层依赖的系统模块或功能,因此调用时会触发找不到模块或未知错误的异常。
兼容方案
如果需要兼容旧版Windows系统,可以改用Win32原生API实现文件修改时间的获取,例如使用GetFileTime函数,示例如下:
#include <fstream> #include <iostream> #include <windows.h> #include <chrono> #include <filesystem> int main() { const auto file_path = std::filesystem::temp_directory_path() / "last_write_time.txt"; std::ofstream(file_path.c_str()) << "Hello, World!"; HANDLE hFile = CreateFileW(file_path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile != INVALID_HANDLE_VALUE) { FILETIME ftWrite; if (GetFileTime(hFile, nullptr, nullptr, &ftWrite)) { // 转换为std::chrono时间点 ULARGE_INTEGER ul; ul.LowPart = ftWrite.dwLowDateTime; ul.HighPart = ftWrite.dwHighDateTime; auto duration = std::chrono::microseconds(ul.QuadPart * 10); auto ftime = std::chrono::file_time_type(duration); std::cout << "Last write time: " << ftime.time_since_epoch().count() << std::endl; } else { std::cerr << "GetFileTime failed: " << GetLastError() << std::endl; } CloseHandle(hFile); } else { std::cerr << "CreateFile failed: " << GetLastError() << std::endl; } std::filesystem::remove(file_path); }
内容的提问来源于stack exchange,提问作者Kevin Haybach
相关产品推荐
相关产品推荐

