c++如何遍历目录下的所有文件_c++遍历文件系统目录的方法
发布时间:2025-10-31 20:28
发布者:网络
浏览次数:
在C++中遍历目录下的所有文件,可以使用不同方法,具体取决于你使用的平台和标准库支持程度。以下是几种常见且实用的方式。
使用 C++17 的 std::filesystem(推荐)
从 C++17 开始,标准库提供了 std::filesystem 模块,可以跨平台地遍历目录,无需依赖第三方库。
你需要包含头文件 filesystem 并使用 std::filesystem::directory_iterator 或 recursive_directory_iterator 来遍历。
示例代码:
微尔企业网站管理系统动态智能版1.1 build 101029
* 包含企业网所需要要的所有常用功能 * 单页企业信息页面(如公司简介、联系方式等类似页面)可以自由增加删除,自己设置文件名 * 完整的产品功能模块 * 人才招聘模块,可以直接在线提交简历 * 新闻文章模块,可自由设置二级文章分类,并对每个分类使用不同模板,如定制某个文章分类为图片分类,视频分类等 * 扩展功能包含公告、留言、友情链接等 把本系统解压到网站根目录即可使用 后台管理目录:
0
查看详情
#include <iostream>
#include <filesystem>
<p>namespace fs = std::filesystem;</p><p>void tr*erse_directory(const std::string& path) {
for (const auto& entry : fs::directory_iterator(path)) {
std::cout << entry.path() << "
";
}
}</p><p>// 递归遍历子目录
void tr*erse_recursive(const std::string& path) {
for (const auto& entry : fs::recursive_directory_iterator(path)) {
std::cout << entry.path() << "
";
}
}</p><p>int main() {
std::string dir = "."; // 当前目录
tr*erse_directory(dir);
return 0;
}
编译时注意: 需要启用 C++17 并链接 stdc++fs(GCC),例如:
g++ -std=c++17 your_file.cpp -lstdc++fs
使用 POSIX opendir / readdir(Linux/Unix)
在类 Unix 系统中,可以使用
示例代码:
#include <iostream>
#include <dirent.h>
<p>void tr*erse_posix(const std::string& path) {
DIR* dir = opendir(path.c_str());
if (!dir) {
std::cerr << "无法打开目录: " << path << "
";
return;
}</p><pre class="brush:php;toolbar:false;">struct dirent* entry;
while ((entry = readdir(dir)) != nullptr) {
std::string name = entry->d_name;
if (name != "." && name != "..") {
std::cout << path + "/" + name << "
";
}
}
closedir(dir);}
该方法不支持递归遍历子目录中的子目录自动展开,需手动判断类型并递归调用。
使用 Windows API(Windows 平台)
在 Windows 上,可以使用 FindFirstFile 和 FindNextFile 函数遍历目录。
示例代码:
#include <iostream>
#include <windows.h>
<p>void tr*erse_windows(const std::string& path) {
std::string searchPath = path + "*";
WIN32_FIND_DATA data;
HANDLE hFind = FindFirstFile(searchPath.c_str(), &data);</p><pre class="brush:php;toolbar:false;">if (hFind == INVALID_HANDLE_VALUE) {
std::cerr << "无法打开目录
";
return;
}
do {
std::string name = data.cFileName;
if (name != "." && name != "..") {
std::cout << path + "\" + name << "
";
}
} while (FindNextFile(hFind, &data));
FindClose(hFind);}
适用于原生 Windows 编程,但不具备跨平台性。
小结与建议
如果你的编译器支持 C++17,强烈推荐使用 std::filesystem,它简洁、安全、跨平台。
若项目受限于旧标准或特定平台,可选择对应平台的 API 实现。
基本上就这些方法,根据环境选择即可。
以上就是c++++如何遍历目录下的所有文件_c++遍历文件系统目录的方法的详细内容,更多请关注其它相关文章!
# c++
# 目录遍历
# linux
# windows
# ai
# unix
# ios
# win
# stream
# 标准库
# 遍历
# 递归
# 管理系统
# 企业网站
# 可以使用
# 文件系统
# 目录下
# 推荐使用
# 并与
# 多线程
# 网站建设管理情况说明
# 网站搜索优化nh金手指靠谱
# 浙江网站建设售后服务
# 重庆seo排名方法最新
# 兴化市关键词优化排名
# 广州网站排名如何推广
# 湖北创新网站推广优势
# 深圳婚庆网站建设
# 东营网站建设作用大吗
# 藁城区行业网站推广案例




