#include <dirent.h>
#include <iostream>
#include <regex>
#include <string>
std::vector<std::string> faceDescriptorManager::get_all_files(std::string path, std::string suffix)
{
std::vector<std::string> files;
files.clear();
DIR *dp;
struct dirent *dirp;
if((dp = opendir(path.c_str())) == NULL)
{
cout << "Can not open " << path << endl;
return files;
}
regex reg_obj(suffix, regex::icase);
while((dirp = readdir(dp)) != NULL)
{
if(dirp -> d_type == 8)
{
if(regex_match(dirp->d_name, reg_obj))
{
string all_path = path + dirp->d_name;
files.push_back(all_path);
cout << dirp->d_name << " " << dirp->d_ino << " " << dirp->d_off << " " << dirp->d_reclen << " " << dirp->d_type << endl;
}
}
}
closedir(dp);
return files;
}
- 上一个方法只能获取文件夹下的文件,如果需要获得所有子文件夹里的所有特定后缀名的文件,可用以下方法
#include <regex>
#include <string>
#include <vector>
#include <dirent.h>
#include <iostream>
using namespace std;
std::vector<std::string> get_all_files(std::string path, std::string suffix)
{
std::vector<std::string> files;
regex reg_obj(suffix, regex::icase);
std::vector<std::string> paths;
paths.push_back(path);
for(int i = 0; i < paths.size(); i++)
{
string curr_path = paths[i];
DIR *dp;
struct dirent *dirp;
if((dp = opendir(curr_path.c_str())) == NULL)
{
cerr << "can not open this file." << endl;
continue;
}
while((dirp = readdir(dp)) != NULL)
{
if(dirp->d_type == 4)
{
if((dirp->d_name)[0] == '.')
continue;
string tmp_path = curr_path + "/" + dirp->d_name;
paths.push_back(tmp_path);
}
else if(dirp->d_type == 8)
{
if(regex_match(dirp->d_name, reg_obj))
{
string full_path = curr_path + "/" + dirp->d_name;
files.push_back(full_path);
}
}
}
closedir(dp);
}
return files;
}