gpt4 book ai didi

c++ - 如何比较 time_t 和 std::filesystem::file_time_type

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:15:32 54 4
gpt4 key购买 nike

我正在将一些代码从 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/

54 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com