我正在将一些代码从 boost::filesystem
转换到 std::filesystem
。以前使用的代码 boost::filesystem::last_write_time()
它返回一个 time_t
,因此直接与我已经持有的 time_t
对象进行比较是微不足道的。顺便说一句,我持有的这个 time_t
是从很久以前保存的文件内容中读取的,所以我坚持使用这种“自 unix 纪元以来的时间”类型。
std::filesystem::last_write_time
返回 std::filesystem::file_time_type
.是否有可移植的方法将 file_time_type
转换为 time_t
,或者以其他方式可移植地比较两个对象?
#include <ctime>
#include <filesystem>
std::time_t GetATimeInSecondsSince1970Epoch()
{
return 1207609200; // Some time in April 2008 (just an example!)
}
int main()
{
const std::time_t time = GetATimeInSecondsSince1970Epoch();
const auto lastWriteTime = std::filesystem::last_write_time("c:\\file.txt");
// How to portably compare time and lastWriteTime?
}
编辑:请注意 sample code at cppreference.com for last_write_time
声明它假设时钟是 std::chrono::system_clock
它实现了 to_time_t
函数。这个假设并不总是正确的,也不在我的平台上 (VS2017)。
最佳答案
Fwiw,当 C++20 到来时,可移植的解决方案将是:
clock_cast<file_clock>(system_clock::from_time_t(time)) < lastWriteTime
这会将 time_t
转换为 file_time
,反之亦然。这种方法的优点是 file_time
通常比 time_t
具有更高的精度。将 file_time
转换为 time_t
会在转换过程中失去精度,因此可能会导致比较不准确。
关于c++ - 如何比较 time_t 和 std::filesystem::file_time_type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51273205/