我使用MSVC2015为windows编写了一个解决方案,其中下面的代码将std::filesystem::last
_
写
_
时间结果时间
_
t:
time_t ftime = std::file_time_type::clock::to_time_t(fs::last_write_time("/Path/filename"))它工作得很好。然后,当我尝试使用GCC9.3 (-std=C++2a)将解决方案移植到Linux时,我得到了以下错误:
错误:'to
_
时间
_
t‘不是'std::chrono::time’的成员
_
point::clock‘{aka 'std::filesystem::
_
_
文件
_
时钟‘}
我寻找了一个解决方案,但我找到的是基于std::filesystem::last示例中包含的解决方案
_
写
_
时间
cplusplus.com
..。解决方案如下所示:
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进行此转换?
发布于 2020-04-07 03:18:24
如前所述,在C++17中没有完美的方法可以做到这一点,根据实际的用例,使用可移植的近似值可能已经足够好了。根据我对以下问题的回答
“如何转换
转换为使用GCC 9的字符串“
,我想推荐在那里使用的helper函数:
template
std::time_t to_time_t(TP tp)
{
using namespace std::chrono;
auto sctp = time_point_cast(tp - TP::clock::now()
+ system_clock::now());
return system_clock::to_time_t(sctp);
}请注意,它使用调用
在每个时钟上,因此它不是一个精确的、往返保证的解决方案,但它可能对您有用,直到库中的差距被关闭。它是基于这样一个事实,即同一时钟的时间点之间的差异很容易,并且存在一个
对于
和
不同来源的。
有关进一步降低相关错误风险的方法,我想指出
C++11时钟之间的转换
其中进行了一些统计分析,以减少可能的错误,但当可以接受时,我只使用上面的代码。
发布于 2020-04-04 23:35:27
在C++20之前?没有可移植的方法可以做到这一点。它在该版本的Visual Studio中工作,因为该版本的VS的文件系统实现恰好使用
对于文件系统时钟类型。这不是C++标准所要求的,但它是允许的。所以你的代码恰好可以工作。
在C++20之前,没有将两个时钟对齐的机制,因此一个时钟的时间可以转换为另一个时钟的时间。所以如果文件系统时钟
不是
你真不走运。您必须使用该实现如何实现其文件系统时钟的知识(基本上知道它使用的是什么时期)来编写特定于该实现的代码,以便可以手动将其转换为
..。
C++20给出了
要在所有实现中使用的固定时期(UNIX时间),并要求
能够将其时间点转换为
时间点。
发布于 2021-01-19 00:49:32
在深入研究之后,我设法重写了他们给出的示例,并且似乎可以工作;关键是转换为
然后转到
..。
#include
#include
#include
#include
#include
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);
}https://stackoverflow.com/questions/61030383
复制相似问题