通过使用 std::filesystem 库中的 std::filesystem::last_write_time 函数,可在 c++++ 中获取文件的最后修改时间,该函数返回一个 std::chrono::file_time_type 对象,可转换为 time_t 类型以进行进一步处理或输出。
如何使用 C++ 获取文件最后修改时间
在 C++ 中,我们可以使用 std::filesystem 库来获取文件和目录的各种信息,包括文件最后修改时间。
头文件
立即学习“C++免费学习笔记(深入)”;
#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++获取文件最后修改时间?的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号