将最后修改时间的字符串表示转换回其类型(std::filesystem::file_time_type)
Converting string representation of last modification time back to its type(std::filesystem::file_time_type)
我做了一个函数,它使用 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 that works with data type std::filesystem::file_time_type。
背景:需要字符串解释,因为我通过网络发送这些数据,然后在收到这个时间后,我使用它并更改另一个文件的最后修改时间,使它们具有相同的时间。
lastWriteTime 方法的示例输出:
1568045082
在 C++20 的完整 date/time 内容出现之前,除了存储它并将其与另一个 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++ 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 that works with data type std::filesystem::file_time_type。
背景:需要字符串解释,因为我通过网络发送这些数据,然后在收到这个时间后,我使用它并更改另一个文件的最后修改时间,使它们具有相同的时间。
lastWriteTime 方法的示例输出: 1568045082
在 C++20 的完整 date/time 内容出现之前,除了存储它并将其与另一个 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
也需要相同。