新建一个dir.h,声明dir类
#ifndef DIR_H
#define DIR_H#include <sys/types.h>#include <dirent.h>
#include <stdio.h>
#include <string.h>#include <iostream>
#include <list>class Dir
{
public:Dir();static std::list<std::string> entryList(const char *dirPath, const char *filter);
};#endif // DIR_H
新建一个dir.cpp,定义dir类
#include "dir.h"Dir::Dir()
{}std::list<std::string> Dir::entryList(const char *dirPath, const char *filter)
{std::list<std::string> list;DIR * fp = opendir(dirPath);if(fp == NULL){perror("opendir error");return list;}while(1){struct dirent * info = readdir(fp);if(info == NULL){break;}if(info->d_type == DT_REG && info->d_name[0] != '.' &&strstr(info->d_name,filter)!=NULL){//获取文件名char text[1024] = {0};if(dirPath[strlen(dirPath)-1] == '/'){sprintf(text,"%s%s",dirPath,info->d_name);}else{sprintf(text,"%s/%s",dirPath,info->d_name);}//存储到 链表容器中list.push_back(text);}}return list;
}
调用方法
//返回当前目录下以txt结尾的文件
std::list<string> list = Dir::entryList("./",".txt");