C 遍历目录及其子目录
2024-09-06 08:10:09
遍历某一目录,获取该目录下所有文件路径的数组
#include <iostream>
#include <dirent.h>
#include <vector> void listDir(char *path, std::vector<std::string> *files)
{
DIR *directory_pointer;
struct dirent *entry;
char childpath[]; //定义一个字符数组,用来存放读取的路径
char filepath[]; //定义一个字符数组,用来存放读取的路径
directory_pointer=opendir(path);
memset(childpath,,sizeof(childpath)); //将字符数组childpath的数组元素全部置零
while((entry=readdir(directory_pointer))!=NULL) //读取pDir打开的目录,并赋值给ent, 同时判断是否目录为空,不为空则执行循环体
{
if(entry->d_type & DT_DIR) //读取 打开目录的文件类型 并与 DT_DIR进行位与运算操作,即如果读取的d_type类型为DT_DIR (=4 表读取的为目录)
{
if(strcmp(entry->d_name,".")== || strcmp(entry->d_name,"..")==)
{
//如果读取的d_name为 . 或者.. 表示读取的是当前目录符和上一目录符, 用contiue跳过,不进行下面的输出
continue;
} sprintf(childpath,"%s/%s",path,entry->d_name); //如果非. ..则将 路径 和 文件名d_name 付给childpath, 并在下一行prinf输出
//printf("path:%s\n",childpath);
listDir(childpath, files); //递归读取下层的字目录内容, 因为是递归,所以从外往里逐次输出所有目录(路径+目录名),
//然后才在else中由内往外逐次输出所有文件名
}
else //如果读取的d_type类型不是 DT_DIR, 即读取的不是目录,而是文件,则直接输出 d_name, 即输出文件名
{
sprintf(filepath,"%s/%s",path,entry->d_name);
printf("file path:%s\n",filepath); //输出文件名 带上了目录
files->push_back(filepath);
}
}
} int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "ListFile Start!\n"; std::string res = "res";
char *path = const_cast<char *>(res.c_str());
std::vector<std::string> files;
listDir(path, &files);
return ;
}
运行结果:
最新文章
- SQL Server删除重复行的6个方法
- second class
- 移动端H5-第一课css篇
- select、epoll、twisted网络编程
- 用 Python 和 OpenCV 检测图片上的条形码
- Android数据存储(一)----SharedPreferences详解
- Java和C#运行速度对比:Java比C#快约3倍
- iframe 中嵌套刷新
- shell之变量替换:临时替换
- c#代码规范和质量检查工具这点事
- 关于阻止PROE联网的一些想法!
- 手写代码 - java.util.List 相关
- [LeetCode] Inorder Successor in BST II 二叉搜索树中的中序后继节点之二
- 背水一战 Windows 10 (115) - 后台任务: 通过 toast 激活后台任务, 定时激活后台任务
- hive数据查询
- 手动更新nexus的索引
- MAC 查看端口占用
- HDU4054_Hexadecimal View
- 使用tc对linux中某ip段限速
- 技术总结PHP+微信