C++ 获取指定文件夹下指定后缀名文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kunyXu/article/details/78864459
#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;
}

猜你喜欢

转载自blog.csdn.net/kunyXu/article/details/78864459