简体   繁体   English

C ++查找文件夹中所有类型的文件?

[英]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++. 我已经找到了使用dirent.h的示例,但是我需要在直接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 . 可以不这样做“直C ++”,因为C ++没有一个文件系统API

I'd traditionally recommend Boost.Filesystem here, but you allegedly want to "avoid using third party headers if [you] can". 传统上,我会在这里推荐Boost.Filesystem,但是据称您希望“如果可以的话,避免使用第三方头文件”。

So your best bet is to use POSIX dirent.h , as you have been doing all along. 因此,最好的选择是使用POSIX dirent.h ,就像您一直以来所做的那样。 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'. 这将在您指定的文件夹中找到所有suid文件,但可以进行修改以查找任意数量的内容,或者如果您用“类型”表示扩展名,则使用正则表达式作为扩展名。

#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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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