读取文件夹中文件名字存入数组

#include<dirent.h>
vector<string> getFilesList(string dirpath){
    DIR *dir = opendir(dirpath.c_str());
    if (dir == NULL)
    {
        cout << "opendir error" << endl;
    }
 
    vector<string> allPath;
    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL)
    {
        if (entry->d_type == DT_DIR){//It's dir
            if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
                continue;
            string dirNew = dirpath + "/" + entry->d_name;
            vector<string> tempPath = getFilesList(dirNew);
            allPath.insert(allPath.end(), tempPath.begin(), tempPath.end());
 
        }else {
            //cout << "name = " << entry->d_name << ", len = " << entry->d_reclen << ", entry->d_type = " << (int)entry->d_type << endl;
            string name = entry->d_name;
            string imgdir = dirpath +"/"+ name;
            //sprintf("%s",imgdir.c_str());
            allPath.push_back(imgdir);
        }
 
    }
    sort(allPath.begin(), allPath.end());
    closedir(dir);
    //system("pause");
    printf("Load %d images!",(int)allPath.size());
    return allPath;
}

 

posted @ 2022-03-11 09:51  开锁球  阅读(173)  评论(0)    收藏  举报