我正在将一些代码从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)。
答案 0 :(得分:4)
首先,当C ++ 20出现时,便携式解决方案将是:
**********
这会将clock_cast<file_clock>(system_clock::from_time_t(time)) < lastWriteTime
转换为time_t
,反之亦然。这种方法的优点是file_time
的精度通常比file_time
高。将time_t
转换为file_time
会降低转换过程中的精度,因此有使比较不准确的风险。
答案 1 :(得分:3)
您链接的那篇文章展示了如何执行此操作:通过to_time_t
的相应clock
的{{1}}成员。
通过您自己的链接复制粘贴:
file_time_type
如果您的平台没有给您auto ftime = fs::last_write_time(p);
std::time_t cftime = decltype(ftime)::clock::to_time_t(ftime);
作为system_clock
的时钟,那么将没有任何可移植的解决方案(至少file_time_type
时钟为C ++ 20)已标准化)。在此之前,您必须确定时钟的实际时间,然后通过file_time_type
和朋友适当地投放时间。
答案 2 :(得分:0)
我遇到了同样的问题,并使用专用的Visual Studio代码解决了这个问题。
对于VS,我使用_wstati64
函数(宽字符为w
,因为Windows在Utf16中编码Unicode路径)和wstring
的{{1}}转换课。
整个事情都收集在这个函数中:
path