简体   繁体   中英

C++ find all files of type in folder?

I am trying to list all the files of a certain type in a folder, so that I can loop through them. This should be simple, surely, but I can't get it. I have found some example using dirent.h, but I need to do this in straight c++.

What is the best way to go about this?

Thanks.

You cannot do this in "straight C++", because C++ does not have a filesystem API yet .

I'd traditionally recommend Boost.Filesystem here, but you allegedly want to "avoid using third party headers if [you] can".

So your best bet is to use POSIX dirent.h , as you have been doing all along. It's about as "non-third party" as you're going to get for the time being.

Something like this? This finds all suid files in folders you specify, but can be modified to find any number of things, or use a regex for the extension if that is what you mean by 'type'.

#include <sys/stat.h>
#include <sys/types.h>
#include <iostream>
#include <string>
#include <sstream>
#include <dirent.h>
#include <vector>


bool is_suid(const char *file)
{
  struct stat results;
  stat(file, &results);
  if (results.st_mode & S_ISUID) return true;
  return false;
}


void help_me(char *me) {
  std::cout
  << "Usage:" << std::endl
  << " " << me << " /bin/ /usr/sbin/ /usr/bin/ /usr/bin/libexec/" << std::endl;
  exit(1);  
}


int main(int argc, char **argv)
{
  if (argc < 2) help_me(argv[0]);
  std::string file_str;
  std::vector<std::string> file_list;
  for (int path_num = 1; path_num != argc; path_num++) {
    const char * path = argv[path_num];
    DIR *the_dir;
    struct dirent *this_dir;
    the_dir = opendir(path);
    if (the_dir != NULL) while (this_dir = readdir(the_dir)) file_list.push_back(std::string(this_dir->d_name));
    std::string name;
    for(int file_num = 0; file_num != file_list.size(); file_num++) {
      name = file_list[file_num];
      std::string path_to_file = std::string(path) + file_list[file_num];
      if (is_suid(path_to_file.c_str()) == true) std::cout << path_to_file << std::endl;
    }
    file_list.clear();
    file_list.shrink_to_fit();
  }
  exit(0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM