C++获取目录下所有文件

#include <io.h>
#include <cstring>
#include <iostream>
#include <glog/logging.h>
#include <string>
#include <vector>

// Get All Files by Dir
void GetAllFilesByDir(const char* dir_path, std::vector<std::string>& img_dir);
// Get File Name By file path
std::string GetFileNameByPath(const std::string& file_path);

void  GetAllFilesByDir(const char* dir_path, std::vector<std::string>& img_dir) {
    intptr_t handle;
    _finddata_t find_data;
    std::string path_name;

    handle = _findfirst(path_name.assign(dir_path).append("\\*").c_str(), &find_data);
    if (handle == -1) {
        LOG(ERROR) << "[retinaface]:" << "when deal Columbia Gaze Data Set, get images by dir error ";
        return ;
    }
    do {
        if (find_data.attrib & _A_SUBDIR) {

            if (strcmp(find_data.name, ".") != 0 && strcmp(find_data.name, "..") != 0) {
                std::string tmp(dir_path);
                GetAllFilesByDir(tmp.append("/").append(find_data.name).c_str(), img_dir);
            }
        }else {
            std::string tmp(dir_path);
            img_dir.push_back(tmp.append("/").append(find_data.name));
        }
    } while (_findnext(handle, &find_data) == 0); // find next images
    _findclose(handle);
}

std::string GetFileNameByPath(const std::string& file_path) {
    auto it = file_path.find_last_of("/");
    string file_name = file_path.substr(it+1, file_path.size() - it);
    return file_name;
}

int main(int argc, char** argv) {
    std::string dir_path = "../../../data/images";
    std::vector<std::string> images_name;
    GetAllFilesByDir(dir_path.c_str(), images_name);
    for (auto& it : images_name) {
        LOG(INFO) << it;
    }
    return 0;
}
posted @ 2021-04-12 15:01  cyssmile  阅读(908)  评论(0)    收藏  举报