我使用 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"))
Run Code Online (Sandbox Code Playgroud)
它运作良好。然后,当我尝试使用 gcc 9.3 (-std=C++2a) 将解决方案移植到 Linux 时,出现以下错误:
错误:'to_time_t' 不是 'std::chrono::time_point::clock' {aka 'std::filesystem::__file_clock'} 的成员
我搜索了一个解决方案,但我发现是基于解决方案包括上例中的std ::文件系统:: last_write_time在cplusplus.com。解决方法如下图:
auto ftime = fs::last_write_time(p);
std::time_t cftime = decltype(ftime)::clock::to_time_t(ftime);
Run Code Online (Sandbox Code Playgroud)
不幸的是,它对我不起作用。实际上,该示例有一条评论说它不适用于 MSVC(曾在 MSVC2015 上工作)或 GCC 9;C++20 将允许便携式输出。
现在,我被卡住了……我怎样才能使用 gcc 进行这种转换?
kor*_*123 16
C++20解决方案
const auto fileTime = std::filesystem::last_write_time(filePath);
const auto systemTime = std::chrono::clock_cast<std::chrono::system_clock>(fileTime);
const auto time = std::chrono::system_clock::to_time_t(systemTime);
Run Code Online (Sandbox Code Playgroud)
Gul*_*rak 12
如前所述,在 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);
}
Run Code Online (Sandbox Code Playgroud)
请注意,它使用now()对每个时钟的调用,因此它不是一个精确的、往返保证的解决方案,但它可能对您有用,直到库中的间隙关闭。它是基于一个事实,即在同一时钟的时间点之间的差异是容易的,有一个operator+用于duration和time_point不同来源。
对于进一步降低相关错误风险的方法,我想指出C++11 时钟之间的转换,其中进行了一些统计分析以减少可能的错误,但在可接受的情况下,我只使用上面的代码。
在 C++20 之前?没有便携式方法可以做到这一点。它在那个版本的 Visual Studio 中工作,因为那个版本的 VS 文件系统实现恰好system_clock用于文件系统时钟类型。这不是 C++ 标准所要求的,但它是允许的。所以你的代码碰巧起作用了。
在 C++20 之前,没有将两个时钟对齐的机制,因此可以将一个时钟的时间转换为另一个时钟的时间。因此,如果文件系统时钟不是 system_clock,那么您就不走运了。您必须使用该实现如何实现其文件系统时钟的知识(基本上知道它使用哪个纪元)来编写特定于实现的代码,以便您可以手动将其转换为system_clock::time_point.
C++20 提供system_clock了一个在所有实现中使用的固定纪元(UNIX 时间),并要求file_clock能够将其时间点转换为system_clock时间点。
小智 5
经过一番挖掘后,我设法重写了他们给出的示例,它似乎有效;关键是转换为system_clockthen 到time_t。
#include <iostream>
#include <chrono>
#include <iomanip>
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
using namespace std::chrono_literals;
int main()
{
fs::path p = fs::current_path() / "example.bin";
std::ofstream(p.c_str()).put('a'); // create file
auto ftime = fs::last_write_time(p);
auto cftime = std::chrono::system_clock::to_time_t(std::chrono::file_clock::to_sys(ftime));
std::cout << "File write time is " << std::asctime(std::localtime(&cftime)) << '\n';
fs::last_write_time(p, ftime + 1h); // move file write time 1 hour to the future
ftime = fs::last_write_time(p); // read back from the filesystem
cftime = std::chrono::system_clock::to_time_t(std::chrono::file_clock::to_sys(ftime));
std::cout << "File write time is " << std::asctime(std::localtime(&cftime)) << '\n';
fs::remove(p);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3907 次 |
| 最近记录: |