Home > Backend Development > C++ > How to get the last modification time of a file using C++?

How to get the last modification time of a file using C++?

王林
Release: 2024-06-04 13:42:56
Original
988 people have browsed it

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 get the last modification time of a file using C++?

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>
Copy after login

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;
Copy after login

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;
Copy after login

The output is similar to:

Last modification time: Thu Jul 21 18:09:35 2023
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template