- 1 year ago
C++ on Visual Studio 2022 last_write_time returns huge number
If the last_write_time
function in C++ on Visual Studio 2022 is returning a huge number instead of the expected file modification timestamp, it may be due to a mismatch in the data type used to store the timestamp. The last_write_time
function returns a file_time_type
object, which is a std::filesystem::file_time_type
representing the file's timestamp.
To properly display the file modification timestamp, you need to convert the file_time_type
to a more readable format, such as a std::chrono::system_clock::time_point
. Here's an example of how you can achieve this:
cpp#include <iostream>
#include <filesystem>
#include <chrono>
int main() {
std::filesystem::path filePath = "path_to_your_file";
std::filesystem::file_time_type fileTime = std::filesystem::last_write_time(filePath);
std::chrono::system_clock::time_point timePoint = std::chrono::time_point_cast<std::chrono::system_clock::duration>(fileTime - std::filesystem::file_time_type::clock::now()
+ std::chrono::system_clock::now());
std::time_t t = std::chrono::system_clock::to_time_t(timePoint);
std::cout << "Last modified: " << std::ctime(&t);
return 0;
}
In this example, we use std::filesystem::last_write_time
to obtain the file_time_type
object representing the file's timestamp. We then perform some conversions to convert it to a std::chrono::system_clock::time_point
. Finally, we use std::chrono::system_clock::to_time_t
and std::ctime
to convert and display the timestamp in a readable format.
Make sure to replace "path_to_your_file"
with the actual path to the file you want to check.
By applying these modifications, you should be able to obtain and display the file modification timestamp correctly in your C++ code on Visual Studio 2022.