C++ How to search files in a directory with certain name? -
i want find files start words. example abc , abc22424 , abc44646, abc353535 found on other question. please me. new in c++
#include <sys/types.h> #include <dirent.h> #include <errno.h> #include <vector> #include <string> #include <iostream> using namespace std; int getdir (string dir, vector<string> &files) { dir *dp; struct dirent *dirp; if((dp = opendir(dir.c_str())) == null) { cout << "error(" << errno << ") opening " << dir << endl; return errno; } while ((dirp = readdir(dp)) != null) files.push_back(string(dirp->d_name)); closedir(dp); return 0; } int main() { string dir = string("c:\\test"); vector<string> files = vector<string>(); getdir(dir,files); (unsigned int = 0;i < files.size();i++) cout << files[i] << endl; return 0; }
now can file names. compare file name.
while ((dirp = readdir(dp)) != null) { std::string fname = dirp->d_name; if(fname.find("abc") != std::string::npos) files.push_back(fname); }
also can use scandir function can register filter function.
static int filter(const struct dirent* dir_ent) { if (!strcmp(dir_ent->d_name, ".") || !strcmp(dir_ent->d_name, "..")) return 0; std::string fname = dir_ent->d_name; if (fname.find("abc") == std::string::npos) return 0; return 1; } int main() { struct dirent **namelist; std::vector<std::string> v; std::vector<std::string>::iterator it; n = scandir( dir_path , &namelist, *filter, alphasort ); (int i=0; i<n; i++) { std::string fname = namelist[i]->d_name; v.push_back(fname); free(namelist[i]); } free(namelist); return 0; }
Comments
Post a Comment