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

标签 c++ c++-chrono boost-filesystem

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

相关文章:

android - Android NDK 部分不支持计时

c++ - 同时获取steady_clock和system_clock

windows - 为什么 boost::filesystem is_directory 在作为 Windows 服务运行时返回不同的结果?

c++ - boost::filesystem::exists 崩溃

c++ - Eclipse CDT 基于文件构建/运行

c++ - 如何在 C 中打印值而不指定它们的类型,就像在 C++ 中使用 "cerr << (A) << endl"一样?

c++ - Qt Creator 中的文件 I/O is_open() 失败

c++ - 断点如何在 C++ 代码中工作?

c++ - 如何在 C++17 中检索 std::filesystem::file_time_type 的时钟类型

c++ - Boost 无法打开文件, 'libboost_filesystem-vc100-mt-gd-1_47.lib'