如何用C++ <filesystem>库查找目录中最新的.mkv文件?
使用C++ 查找目录中最新的.mkv文件的有效方法
要实现这个需求,核心思路是遍历目标目录下的所有文件,过滤出.mkv后缀的文件,然后比较它们的最后修改时间,最终锁定时间最新的那个。以下是具体实现步骤和代码:
核心步骤
- 遍历目标目录,跳过子目录(若需要包含子目录可改用
recursive_directory_iterator) - 对每个文件,检查扩展名是否为
.mkv(如需忽略大小写可额外处理) - 获取每个符合条件文件的最后修改时间
- 维护变量记录当前最新文件及其修改时间,遍历过程中持续更新
完整代码示例
#include <filesystem> #include <iostream> #include <string> #include <stdexcept> #include <algorithm> namespace fs = std::filesystem; fs::path find_newest_mkv(const fs::path& target_dir) { // 校验目录有效性 if (!fs::exists(target_dir) || !fs::is_directory(target_dir)) { throw std::invalid_argument("目标目录不存在或不是有效目录"); } fs::path newest_file; std::filesystem::file_time_type newest_time{}; // 遍历目录条目 for (const auto& entry : fs::directory_iterator(target_dir)) { // 跳过非普通文件 if (!entry.is_regular_file()) { continue; } const auto& file_path = entry.path(); // 检查扩展名(这里做了大小写不敏感处理) std::string ext = file_path.extension().string(); std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); if (ext == ".mkv") { auto current_time = fs::last_write_time(entry); // 更新最新文件记录 if (current_time > newest_time) { newest_time = current_time; newest_file = file_path; } } } if (newest_file.empty()) { throw std::runtime_error("目录中未找到任何.mkv文件"); } return newest_file; } int main() { try { fs::path target_dir = "./your_target_dir"; // 替换为实际目标目录 auto newest_mkv = find_newest_mkv(target_dir); std::cout << "最新的.mkv文件:" << newest_mkv << std::endl; } catch (const std::exception& e) { std::cerr << "错误:" << e.what() << std::endl; return 1; } return 0; }
注意事项
- C++版本要求:
<filesystem>是C17标准引入的,需确保编译器支持C17及以上(如GCC 8+、Clang 7+、MSVC 2017+) - 编译链接参数:GCC编译时需加
-lstdc++fs,Clang需加-lc++fs,MSVC无需额外参数 - 递归查找子目录:若需要遍历所有子目录,把
fs::directory_iterator替换为fs::recursive_directory_iterator即可 - 时间精度:
last_write_time返回的时间精度取决于操作系统,一般能满足日常需求
内容的提问来源于stack exchange,提问作者Pascal Fischer
相关产品推荐
相关产品推荐

