How to get list of files with a specific extension in a given folder?

前端 未结 6 1913
孤街浪徒
孤街浪徒 2020-11-27 03:29

I want to get the file names of all files that have a specific extension in a given folder (and recursively, its subfolders). That is, the file name (and extension), not th

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 04:22

    Here's my solution (works on *nix systems):

    #include 
    
    bool FindAllFiles(std::string path, std::string type, std::vector &FileList){
      DIR *dir;
      struct dirent *ent;
      FileList.clear();
    
      if ((dir = opendir (path.c_str())) != NULL) {
        //Examine all files in this directory
        while ((ent = readdir (dir)) != NULL) {
          std::string filename = std::string(ent->d_name);
          if(filename.length() > 4){
            std::string ext = filename.substr(filename.size() - 3);
            if(ext == type){
              //store this file if it's correct type
              FileList.push_back(filename);
            }
          }
        }
        closedir (dir);
      } else {
        //Couldn't open dir
        std::cerr << "Could not open directory: " << path << "\n";
        return false;
      }
      return true;
    }
    

    Obviously change the desired extension to whatever you like. Also assumes a 3 character type.

提交回复
热议问题