C++ 查找文件夹下的文件
#include <string> #include <vector> #include <cstring> #include <cstdio> #include <dirent.h> #include <sys/stat.h> #include <sys/types.h> using std::strcmp; using std::string; using std::vector; #if __cplusplus < 201103L #define nullptr NULL #endif #define SEARCH_PATH_LENGTH 1024 /* * 搜索一个文件夹下的符合条件的文件 */ bool searchFile(const char* directory, vector<string>& files, const char* ext, int subdir_level) { const char* dir_path = directory; DIR *dir = nullptr; //打开文件夹 if((dir = opendir(dir_path)) == nullptr) { return false; } struct dirent entry; struct dirent* result; struct stat file_stat; char cur_name[SEARCH_PATH_LENGTH]; //读取文件夹下的一个文件 while(readdir_r(dir, &entry, &result) == 0 && result) { const char* name = entry.d_name; //忽略掉.和.. if(strcmp(name, ".") == 0 || strcmp(name, "..") == 0) continue; //检查拼接路径 int count = sprintf(cur_name, "%s", dir_path); count += sprintf(&cur_name[count], "%s%s", cur_name[count - 1] == '/' ? "" : "/", name); //获取文件的状态 if(lstat(cur_name, &file_stat) != -1) { //文件是普通文件 if(!S_ISDIR(file_stat.st_mode)) { const char* rf = strrchr(cur_name, '.'); //检查文件的后缀名 if(rf != nullptr && strcmp(rf + 1, ext) == 0) files.push_back(string(cur_name, count)); } //文件是文件夹 else if(subdir_level >= 0) { //递归获取下一层目录的文件 searchFile(cur_name, files, ext, subdir_level - 1); } } } closedir(dir); return true; }
araraloren[https://github.com/araraloren/]