【问题标题】:C++ on Visual Studio 2022 last_write_time returns huge numberVisual Studio 2022 上的 C++ last_write_time 返回巨大的数字
【发布时间】:2022-12-08 10:07:56
【问题描述】:
我正在编写一个简单的 c++20 程序来获取文件的最后修改时间。在 MacOS 上,它工作正常,并以秒为单位返回昨天修改的文件的 Unix 纪元时间。但是,在带有 Visual Studio 2022 的 Windows 上,下面的代码返回 Got Modified Time of: 13314844775,根据这里的 Unix 时间戳工具,它是未来 369 年。如何正确转换?
#include <iostream>
#include <filesystem>
#include <chrono>
int main()
{
std::string fileName = "test.txt";
auto modTime = std::filesystem::last_write_time(std::filesystem::path(fileName));
auto epoch = modTime.time_since_epoch();
auto converted = std::chrono::duration_cast<std::chrono::seconds>(epoch);
auto counts = converted.count();
std::cout << "Got Modified Time of: " << counts << std::endl;
}
【问题讨论】:
标签:
c++
windows
visual-studio
c++20
【解决方案1】:
您遇到的问题可能是由于 std::filesystem::last_write_time 函数返回的 std::chrono::time_point 类在 Windows 上使用与在 MacOS 上不同的时间单位。
在 MacOS 上,std::chrono::time_point 类使用的时间单位是std::chrono::system_clock::duration,以秒为单位定义。但是,在 Windows 上,std::chrono::time_point 类使用的时间单位是 std::chrono::file_clock::duration,它以 100 纳秒的间隔定义。
要在 MacOS 和 Windows 上将 std::filesystem::last_write_time 函数返回的时间点正确转换为以秒为单位的 Unix 纪元时间,您需要先使用 std::chrono::file_clock::to_time_t 函数将时间点转换为 std::chrono::system_clock::time_point,然后再将其转换使用 std::chrono::system_clock::to_time_t 函数将时间指向以秒为单位的 Unix 纪元时间。
下面是一个示例,说明如何修改代码以在 MacOS 和 Windows 上将时间点正确转换为以秒为单位的 Unix 纪元时间:
#include <iostream>
#include <filesystem>
#include <chrono>
int main()
{
std::string fileName = "test.txt";
auto modTime = std::filesystem::last_write_time(std::filesystem::path(fileName));
auto systemTime = std::chrono::file_clock::to_time_t(modTime);
auto epoch = std::chrono::system_clock::to_time_t(systemTime);
std::cout << "Got Modified Time of: " << epoch << std::endl;
}
在这段代码中,我们首先使用std::chrono::file_clock::to_time_t函数将std::filesystem::last_write_time函数返回的时间点转换为std::chrono::system_clock::time_point。然后我们使用 std::chrono::system_clock::to_time_t 函数将该时间点转换为以秒为单位的 Unix 纪元时间。这应该在 MacOS 和 Windows 上以秒为单位给出正确的 Unix 纪元时间。