#include <dirent.h>
#include <iostream>
#include <vector>
#include <string>
// Programed by Scourge
// GNU GPLv3
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::vector;
// This is a good method because we can get all the files (with or without folder) recursive or not
// from a target directory, and then have all those elements placed into a vector for easy 'for'
// loop usage and functional parsing.
vector<string> scan_dir(string scan_start, string scope, string include_folder, vector<string> &vec_track){
DIR *current_dir = opendir (scan_start.c_str()); // starting dir given as a string
// "dir_item" can be anything in the "current_dir" such as a new folder, file, binary, etc.
while (struct dirent *dir_item_ptr = readdir(current_dir)){
string dir_item = (dir_item_ptr->d_name); // structure points to the getter to retrive the dir_item's name.
if (dir_item != "." and dir_item != "./" and dir_item != ".."){
if (dir_item_ptr->d_type == DT_DIR){
if(scope == "r" or scope == "-r"){
if(include_folder == "f" or include_folder == "-f"){
vec_track.push_back(dir_item);
}
scan_dir(scan_start + "/"+ dir_item, scope, include_folder, vec_track); // recursive function
}
}else if(dir_item == "read"){
break; // full dir already read, leave the loop
}else{
vec_track.push_back(dir_item);
}
}
}
return vec_track;
closedir (current_dir);
}
int main(){
vector<string> rec_vec;
vector<string> pwd_vec;
// './' as arg 1 sets the target folder to your PWD
scan_dir("./","-r","-f", rec_vec); // "scope" = '-r' = target_folder recursive search
// recursive vector from pwd // "include_folder" = '-f' = include folders in the results
scan_dir("./","-n","-n", pwd_vec); // "scope" = '-n' = use target_folder but not recursive
// pwd vector // "include_folder = '-n' = not folder included
for(string& i: rec_vec){cout << i << endl;} // loop through and print the vector's elements
cout << "---------------------\n";
for(string& i: pwd_vec){cout << i << endl;} // loop through and print the vector's elements
return 0;
}
// My Background. . .
// github.com/Radicalware
// Radicalware.net
// https://www.youtube.com/channel/UCivwmYxoOdDT3GmDnD0CfQA/playlists
出于好奇 - 为什么你要为此做递归使用循环更简单,更清晰,更好的是什么时候? – Krease
特别是如果获得更高维矢量,效率会不会更高? – Flux21
@ Flux21大多数时候你不想拥有一个向量向量。您应该使用单个矢量,并通过使用数学将nD索引转换为1D索引来“伪造”尺寸。 – NathanOliver