
在C++中遍历目录下的所有文件,可以通过多种方式实现。自C++17起,标准库引入了 <filesystem> 头文件,使得文件系统操作变得简单且跨平台。以下介绍基于 std::filesystem 的遍历方法,并提供实用示例。
C++17 提供的 std::filesystem 模块支持目录迭代器,可以轻松遍历指定路径下的所有条目(包括文件和子目录)。
基本步骤如下:
<pre class="brush:php;toolbar:false;">#include <iostream><br>#include <filesystem><br><br>namespace fs = std::filesystem;<br><br>int main() {<br> std::string path = "."; // 当前目录,可替换为任意路径<br><br> try {<br> for (const auto& entry : fs::directory_iterator(path)) {<br> if (entry.is_regular_file()) {<br> std::cout << "文件: " << entry.path().filename() << "\n";<br> } else if (entry.is_directory()) {<br> std::cout << "目录: " << entry.path().filename() << "\n";<br> }<br> }<br> } catch (const fs::filesystem_error& ex) {<br> std::cerr << "访问目录出错: " << ex.what() << "\n";<br> }<br><br> return 0;<br>}编译时需启用 C++17 支持,例如使用 g++:
立即学习“C++免费学习笔记(深入)”;
g++ -std=c++17 -o list_files list_files.cpp
若需要深入子目录查找所有文件,可使用 std::filesystem::recursive_directory_iterator。
它会自动进入子目录,按深度优先顺序遍历所有内容。
示例:递归列出所有文件
<pre class="brush:php;toolbar:false;">#include <iostream><br>#include <filesystem><br><br>namespace fs = std::filesystem;<br><br>int main() {<br> std::string root = ".";<br><br> try {<br> for (const auto& entry : fs::recursive_directory_iterator(root)) {<br> if (entry.is_regular_file()) {<br> std::cout << "发现文件: " << entry.path() << "\n";<br> }<br> }<br> } catch (const fs::filesystem_error& ex) {<br> std::cerr << "错误: " << ex.what() << "\n";<br> }<br><br> return 0;<br>}可以结合文件扩展名进行过滤,比如只列出 .cpp 或 .txt 文件。
通过 path().extension() 获取扩展名并比较。
示例:仅显示 .cpp 文件
<pre class="brush:php;toolbar:false;">for (const auto& entry : fs::directory_iterator(".")) {<br> if (entry.is_regular_file() && entry.path().extension() == ".cpp") {<br> std::cout << "C++ 文件: " << entry.path().filename() << "\n";<br> }<br>}支持多个扩展名判断:
<pre class="brush:php;toolbar:false;">auto ext = entry.path().extension();<br>if (ext == ".cpp" || ext == ".h" || ext == ".hpp") {<br> std::cout << "源码文件: " << entry.path().filename() << "\n";<br>}基本上就这些。使用 std::filesystem 能够以简洁、安全的方式完成目录遍历任务,推荐用于现代C++项目。注意处理异常,并确保目标路径存在且有访问权限。
以上就是c++++中如何遍历一个目录下的所有文件_c++文件系统遍历方法与示例的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号