1. 程式人生 > >C++ 獲取指定資料夾下指定字尾名檔案

C++ 獲取指定資料夾下指定字尾名檔案

#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) // 4 means catalog; 8 means file; 0 means unknown
{ if(regex_match(dirp->d_name, reg_obj)) { // cout << dirp->d_name << endl; 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;
//    files.clear();
    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;
//                cout << dirp->d_name << " ";
                string tmp_path = curr_path + "/" + dirp->d_name;
//                cout << tmp_path << " ";
                paths.push_back(tmp_path);
//                cout << paths[paths.size() - 1] << endl;
            }
            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;
}