我做了一个函数,它使用 C++ filesystem模块获取给定文件的最后修改时间,将其转换为 std::string。
std::string Helper::lastWriteTime(const std::string& itemName)
{
std::filesystem::path file(itemName);
auto time = std::filesystem::last_write_time(file);
std::time_t cftime = decltype(time)::clock::to_time_t(time);
return std::to_string(cftime);
}
但是,现在我想使用这个字符串并将其用作另一个方法的参数 - 该方法转换字符串并根据字符串表示形式更改上次修改时间。方法的相反顺序不起作用,有没有办法实现它?
为了接收文件的最后修改时间,我使用函数 std::filesystem::last_write_time适用于数据类型 std::filesystem::file_time_type .
背景:需要字符串解释,因为我通过网络发送这些数据,然后在收到这次数据后,我使用它并更改另一个文件的上次修改时间,以便它们具有相同的时间。
lastWriteTime 方法的输出示例: 1568045082
最佳答案
在 C++20 的完整日期/时间内容出现之前,除了存储它并将其与另一个 file_time_type
进行比较之外,您无法对 file_time_type
做太多事情。您的 to_time_t
技巧不可移植,因为 file_time_type
不需要是 system_clock
时间。
如果您想存储表示 file_time_type
的整数表示形式的字符串并将其转换回来,那么您应该只获取 time_since_epoch().count()
直接计算时间,而不是使用 to_time_t
体操。您可以通过执行以下操作将整数转换回 file_time_type
:
unsigned long long int_val = ...;
using ft = std::filesystem::file_time_type;
auto the_time = ft(ft::duration(int_val));
当然,只有当源和目标实现使用兼容的文件系统时钟时,这才有效。即使它们使用具有相同纪元的相同时钟,它们的 file_time_type::duration
也需要相同。
关于c++ - 将上次修改时间的字符串表示形式转换回其类型(std::filesystem::file_time_type),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57857914/