【发布时间】:2018-12-18 18:29:13
【问题描述】:
我正在将一些代码从boost::filesystem 转换为std::filesystem。以前的代码使用了boost::filesystem::last_write_time(),它返回一个time_t,所以直接比较我已经持有的time_t对象是微不足道的。顺便说一句,我持有的这个time_t是从很久以前保存的文件内容中读取的,所以我坚持使用这种“自unix epoch以来的时间”类型。
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 声明它假设时钟是实现to_time_t 函数的std::chrono::system_clock。这个假设并不总是正确的,并且不在我的平台上(VS2017)。
【问题讨论】:
-
The documentation 引用
to_time_t,这可能会做你想做的事。 -
C++ 库没有指定将一个时钟上的时间点转换为不同时钟上的等效时间点的方法,而且在许多情况下根本不可能进行转换。我看到的唯一选择是将所有查看文件时间戳的代码转换为使用 last_write_time 的时钟。
-
@tadman 已编辑问题以澄清为什么我无法访问
to_time_t() -
@SamVarshavchik 我尽可能从文件系统的时钟中获取时间点,例如
std::filesystem::file_time_type::clock::now(),但我有这些讨厌的 Unix 纪元时间戳很久以前就存在了。我现在看到这是一个糟糕的决定。猜我需要使用stat()? -
@PeteUK 因为你不在 Unix 文件系统上,所以使用 Unix 时间戳可能不是最好的设计选择。
标签: c++ chrono boost-filesystem