我使用 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 将解决方案移植到 Linux 时(-std=C++2a
),我收到以下错误:
错误:“to_time_t”不是“std::chrono::time_point<:filesystem::_file_clock>::clock”{又名“std::filesystem::__file_clock”}的成员
我搜索了一个解决方案,但我发现的是基于示例中包含的解决方案std::filesystem::last_write_time()
at cplusplus.com https://en.cppreference.com/w/cpp/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++17 中没有完美的方法来做到这一点。根据实际用例,使用便携式近似可能就足够了。根据我的回答“如何转换std::filesystem::file_time_type使用 GCC 9" 转换为字符串 https://stackoverflow.com/questions/56788745/how-to-convert-stdfilesystemfile-time-type-to-a-string-using-gcc-9/58237530#58237530,我想建议那里使用的辅助函数:
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+
for duration
and time_point
不同来源的。
对于进一步降低相关错误风险的方法,我想指出C++11时钟之间的转换 https://stackoverflow.com/questions/35282308/convert-between-c11-clocks进行了一些统计分析
减少可能的错误的想法,但在可接受的情况下,我只使用上面的代码。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)