Ste*_*eve 1 c++ windows visual-studio c++20
我正在编写一个简单的 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;
}
Run Code Online (Sandbox Code Playgroud)
返回值last_write_time是 a time_point,它使用file_clock时钟作为其时间基础。该时钟可能具有也可能不具有与任何其他时钟相同的纪元。纪元是实现定义的。
因此,代码的行为会随着实现而变化。
如果您想获取文件相对于 UNIX 时间的时间,则需要 C++20,它添加了该clock_cast功能。这允许您将时间点转换为相对于不同时钟的时间点。所以你会这样做:
auto modTime = std::filesystem::last_write_time(std::filesystem::path(fileName));
auto modTimeUnix = std::chrono::clock_cast<std::chrono::system_clock>(modTime);
Run Code Online (Sandbox Code Playgroud)
在 C++20 中,system_clock所有实现都需要采用 UNIX 时间,并且file_clock需要能够转换为system_clock.
| 归档时间: |
|
| 查看次数: |
341 次 |
| 最近记录: |