C++列出指定文件夹下所有文件
-
Windows
#include <vector> #include <string> #include <io.h> /** * @brief 列出文件夹下所有指定后缀的文件路径,路径格式为Linux风格 \n - ref 例如 "./images/uuid_2/index_07.txt" \n * @param[in] char * path : 文件夹路径 * @param[out] std::vector<std::string> & allFilePath : 文件路径列表 * @param[in] const char * fileType : 文件后缀 * @return int * @author AILEE * @date 2021-02-03 * @par 示例: * @code * @endcode * @see */ int listFile(char* path, std::vector<std::string>& allFilePath, const char* fileType) { // 列出文件夹下所有文件路径 char dirNew[256]; char file_path[256]; strcpy(file_path, path); strcpy(dirNew, path); strcat(dirNew, "\\*."); strcat(dirNew, fileType); intptr_t handle; _finddata_t findData; handle = _findfirst(dirNew, &findData); if (-1 == handle) { // 检查是否成功 return handle; } do { if (findData.attrib & _A_SUBDIR) { // 排除"."和".."目录 if (strcmp(findData.name, ".") == 0 || strcmp(findData.name, "..") == 0) { continue; } //在目录后加上"//"和搜索到的目录进行下一次搜索 strcpy(dirNew, path); strcat(dirNew, "\\"); strcat(dirNew, findData.name); // 递归 this->listFile(dirNew, allFilePath, fileType); } else { allFilePath.push_back(std::string(file_path) + findData.name); } } while (_findnext(handle, &findData) == 0); _findclose(handle); }
-
Linux
- reference https://phww98.com/index.php/archives/13/
#include <vector> #include <string> #include <unistd.h> #include <dirent.h> /** * @brief 列出路径下所有文件路径 * @param[in] dir 文件夹路径 * @param[in,out] fileList 文件夹路径下所有子文件的路径 * @param[in] type 文件类型 * @return void * @author AILEE * @date 2022/3/18 */ void listFiles(const std::string &dir, std::vector<std::string> &fileList, const std::string& type) { DIR *pDir; ///< 指向根目录结构体的指针 struct dirent *ptr; ///< dirent结构体指针,具体结构看开头的注释 ///< 使用dirent.h下的opendir()打开根目录,并返回指针 if (!(pDir = opendir(dir.c_str()))) { return; } ///< 使用dirent.h下的readdir逐个读取root下的文件 while ((ptr = readdir(pDir)) != nullptr) { std::string sub_file = dir + "/" + ptr->d_name; ///< 当前指针指向的文件名 if (ptr->d_type != 8 && ptr->d_type != 4) { ///< 递归出口,当不是普通文件(8)和文件夹(4)时退出递归 return; } ///< 普通文件 if (ptr->d_type == 8) { ///< 筛选文件 if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) { if (strstr(ptr->d_name, type.c_str())) { fileList.push_back(sub_file); } } } else if (ptr->d_type == 4) { if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) { listFiles(sub_file, fileList, type); } } } // 关闭根目录 closedir(pDir); }