- 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>
),遍历指定类型的文件。