首页 > 解决方案 > 如何将 std::filesystem::file_time_type 转换为 time_t?

问题描述

我使用 MSVC2015 为 windows 编写了一个解决方案,其中以下代码转换 std::filesystem::last_write_time 结果 time_t:

time_t ftime = std::file_time_type::clock::to_time_t(fs::last_write_time("/Path/filename"))

它运作良好。然后,当我尝试使用 gcc 9.3 (-std=C++2a) 将解决方案移植到 Linux 时,出现以下错误:

错误:'to_time_t' 不是 'std::chrono::time_point::clock' {aka 'std::filesystem::__file_clock'} 的成员

我搜索了一个解决方案,但我发现的是基于 cplusplus.com 的 std::filesystem::last_write_time 示例中包含的解决方案。解决方案如下图所示:

auto ftime = fs::last_write_time(p);
std::time_t cftime = decltype(ftime)::clock::to_time_t(ftime);

不幸的是,它对我不起作用。实际上,该示例有一条评论说它不适用于 MSVC(在 MSVC2015 工作)或 GCC 9;C++20 将允许可移植输出。

现在,我被困住了......如何使用 gcc 进行这种转换?

标签: c++chrono

解决方案


如前所述,在 C++17 中没有完美的方法可以做到这一点。根据实际用例,使用可移植的近似值可能就足够了。根据我对"How to convert std::filesystem::file_time_typeto a string using GCC 9" 的回答,我想建议那里使用的辅助函数:

template <typename TP>
std::time_t to_time_t(TP tp)
{
    using namespace std::chrono;
    auto sctp = time_point_cast<system_clock::duration>(tp - TP::clock::now()
              + system_clock::now());
    return system_clock::to_time_t(sctp);
}

请注意,它now()在每个时钟上都使用一个调用,因此它不是一个精确的、保证往返的解决方案,但它可能对您有用,直到库中的空白被关闭。它基于同一时钟的时间点之间的差异很容易并且存在不同来源operator+的事实。durationtime_point

对于进一步降低相关错误风险的方法,我想指出C++11 时钟之间的转换,其中进行了一些统计分析以减轻可能的错误,但在可接受的情况下,我只使用上面的代码。


推荐阅读