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

 #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 ;
}

运行结果:

最新文章

  1. SQL Server删除重复行的6个方法
  2. second class
  3. 移动端H5-第一课css篇
  4. select、epoll、twisted网络编程
  5. 用 Python 和 OpenCV 检测图片上的条形码
  6. Android数据存储(一)----SharedPreferences详解
  7. Java和C#运行速度对比:Java比C#快约3倍
  8. iframe 中嵌套刷新
  9. shell之变量替换:临时替换
  10. c#代码规范和质量检查工具这点事
  11. 关于阻止PROE联网的一些想法!
  12. 手写代码 - java.util.List 相关
  13. [LeetCode] Inorder Successor in BST II 二叉搜索树中的中序后继节点之二
  14. 背水一战 Windows 10 (115) - 后台任务: 通过 toast 激活后台任务, 定时激活后台任务
  15. hive数据查询
  16. 手动更新nexus的索引
  17. MAC 查看端口占用
  18. HDU4054_Hexadecimal View
  19. 使用tc对linux中某ip段限速
  20. 技术总结PHP+微信

热门文章

  1. jQuery 遍历 - eq() 方法
  2. thinkphp session驱动
  3. fastJson中常用方法以及遇到的“坑”
  4. Javascript下拉刷新
  5. Tomcat debug 模式, Application一直reload,导致内存溢出
  6. JVM内核-原理、诊断与优化学习笔记(八):JAVA堆分析
  7. jquery操作html元素之( 获取并设置 CSS 类)
  8. jquery控件的学习
  9. 新手git遇到的问题
  10. IK的整个分词处理过程