菜鸟笔记
提升您的技术认知

C 遍历目录及其子目录

遍历某一目录,获取该目录下所有文件路径的数组

 1 #include <iostream>
 2 #include <dirent.h>
 3 #include <vector>
 4 
 5 void listDir(char *path, std::vector<std::string> *files)
 6 {
 7     DIR *directory_pointer;
 8     struct dirent *entry;
 9     char childpath[512];  //定义一个字符数组,用来存放读取的路径
10     char filepath[512];  //定义一个字符数组,用来存放读取的路径
11     directory_pointer=opendir(path);
12     memset(childpath,0,sizeof(childpath)); //将字符数组childpath的数组元素全部置零
13     while((entry=readdir(directory_pointer))!=NULL)  //读取pDir打开的目录,并赋值给ent, 同时判断是否目录为空,不为空则执行循环体
14     {
15         if(entry->d_type & DT_DIR)  //读取 打开目录的文件类型 并与 DT_DIR进行位与运算操作,即如果读取的d_type类型为DT_DIR (=4 表读取的为目录)
16         {
17             if(strcmp(entry->d_name,".")==0 || strcmp(entry->d_name,"..")==0)
18             {
19                 //如果读取的d_name为 . 或者.. 表示读取的是当前目录符和上一目录符, 用contiue跳过,不进行下面的输出
20                 continue;
21             }
22             
23             sprintf(childpath,"%s/%s",path,entry->d_name);  //如果非. ..则将 路径 和 文件名d_name 付给childpath, 并在下一行prinf输出
24             //printf("path:%s\n",childpath);
25             listDir(childpath, files);  //递归读取下层的字目录内容, 因为是递归,所以从外往里逐次输出所有目录(路径+目录名),
26             //然后才在else中由内往外逐次输出所有文件名
27         }
28         else  //如果读取的d_type类型不是 DT_DIR, 即读取的不是目录,而是文件,则直接输出 d_name, 即输出文件名
29         {
30             sprintf(filepath,"%s/%s",path,entry->d_name);
31             printf("file path:%s\n",filepath); //输出文件名 带上了目录
32             files->push_back(filepath);
33         }
34     }
35 }
36 
37 int main(int argc, const char * argv[]) {
38     // insert code here...
39     std::cout << "ListFile Start!\n";
40     
41     std::string res = "res";
42     char *path = const_cast<char *>(res.c_str());
43     std::vector<std::string> files;
44     listDir(path, &files);
45     return 0;
46 }

运行结果: