通过使用 std::filesystem 库中的 std::filesystem::last_write_time 函数,可在 c++++ 中获取文件的最后修改时间,该函数返回一个 std::chrono::file_time_type 对象,可转换为 time_t 类型以进行进一步处理或输出。
如何使用 C++ 获取文件最后修改时间
在 C++ 中,我们可以使用 std::filesystem 库来获取文件和目录的各种信息,包括文件最后修改时间。
头文件
#include <filesystem>
获取文件最后修改时间
使用 std::filesystem::last_write_time 函数可以获取文件最后修改的时间,返回一个 std::chrono::file_time_type 对象。我们可以使用 std::chrono::system_clock::to_time_t 函数将该时间转换为 time_t 类型,从而可以轻松地输出或进行其他处理。
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;
实战案例
假设我们有一个名为 myfile.txt 的文件,其路径为 c:\my_folder\myfile.txt。我们可以使用以下代码获取该文件的最后修改时间:
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;
输出结果类似于:
Last modification time: Thu Jul 21 18:09:35 2023
以上就是如何使用C++获取文件最后修改时间?的详细内容,更多请关注知识资源分享宝库其它相关文章!
版权声明
本站内容来源于互联网搬运,
仅限用于小范围内传播学习,请在下载后24小时内删除,
如果有侵权内容、不妥之处,请第一时间联系我们删除。敬请谅解!
E-mail:dpw1001@163.com
发表评论