The last modification time of a file can be obtained in C++ by using the std::filesystem::last_write_time function in the std::filesystem library. This function returns a std::chrono::file_time_type object that can be converted to the time_t type. for further processing or output.
How to use C++ to get the last modification time of a file
In C++, we can usestd::filesystem
Library to obtain various information about files and directories, including the last modification time of the file.
Header file
#include <filesystem>
Get the last modification time of the file
Use std::filesystem::last_write_time
The function can get the last modification time of the file and return a std::chrono::file_time_type
object. We can use the std::chrono::system_clock::to_time_t
function to convert this time to the time_t
type so that it can be easily output or otherwise processed.
std::filesystem::path file_path("my_file.txt"); auto last_write_time = std::filesystem::last_write_time(file_path); time_t time = std::chrono::system_clock::to_time_t(last_write_time); std::cout << "Last modification time: " << std::ctime(&time) << std::endl;
Practical case
Suppose we have a file named myfile.txt
with the path c:\my_folder\ myfile.txt
. We can use the following code to get the last modification time of the file:
std::filesystem::path file_path("c:/my_folder/myfile.txt"); auto last_write_time = std::filesystem::last_write_time(file_path); time_t time = std::chrono::system_clock::to_time_t(last_write_time); std::cout << "Last modification time: " << std::ctime(&time) << std::endl;
The output is similar to:
Last modification time: Thu Jul 21 18:09:35 2023
The above is the detailed content of How to get the last modification time of a file using C++?. For more information, please follow other related articles on the PHP Chinese website!