C++实现Linux下遍历指定目录下的文件

来源:互联网 发布:cisco 9396端口配ip 编辑:程序博客网 时间:2024/05/21 18:45

  • c++/readdir.cpp
#include <dirent.h>//遍历系统指定目录下文件要包含的头文件  #include <iostream>  using namespace std;  int main()  {      DIR* dir = opendir("/home/xxx/test");//打开指定目录      dirent* p = NULL;//定义遍历指针      while((p = readdir(dir)) != NULL)//开始逐个遍历      {          //这里需要注意,linux平台下一个目录中有"."和".."隐藏文件,需要过滤掉          if(p->d_name[0] != '.')//d_name是一个char数组,存放当前遍历到的文件名          {              string name = "/home/xxx/test/" + string(p->d_name);              cout<<name<<endl;          }      }      closedir(dir);//关闭指定目录  }  

这里需要注意,由于p->d_name存放的是文件名,所以也可以通过像strstr(p->d_name,".jpg")等来判断(头文件<string.h>),遍历指定类型的文件。

阅读全文
0 0
原创粉丝点击