[英]C++ find all files of type in folder?
我正在嘗試列出文件夾中某種類型的所有文件,以便可以循環瀏覽它們。 當然,這應該很簡單,但我無法理解。 我已經找到了使用dirent.h的示例,但是我需要在直接C ++中執行此操作。
最好的方法是什么?
謝謝。
你可以不這樣做“直C ++”,因為C ++沒有一個文件系統API 還 。
傳統上,我會在這里推薦Boost.Filesystem,但是據稱您希望“如果可以的話,避免使用第三方頭文件”。
因此,最好的選擇是使用POSIX dirent.h ,就像您一直以來所做的那樣。 就目前而言,它就像是“非第三方”。
像這樣嗎 這將在您指定的文件夾中找到所有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.