I have the following code to search all files in a directory and all its sub-directories. the code uses recursion for nested sub-directories.
#include "boost/filesystem.hpp"
#include <iostream>
using namespace boost::filesystem;
void getDirectoryFiles(path p, vector<string> &files) {
if (exists(p)) {
if (is_regular_file(p)) {
files.push_back(p.string());
return;
}
else if (is_directory(p)) {
for (directory_entry& x : directory_iterator(p)) {
getDirectoryFiles(x.path(), files);
}
}
else {
cout << "exists, but not a file of a directory!\n";
return;
}
}
else {
cout << "Path not exists!";
return;
}
};
The general idea taken from Boost documentation with a twist. Any one to optimize this code?
There is a recursive_directory_iterator for that.
Making a sample:
fs::path dir = ".";
fs::recursive_directory_iterator it(dir), end;
std::vector<std::string> files;
for (auto& entry : boost::make_iterator_range(it, end))
if (is_regular(entry))
files.push_back(entry.path().native());
there is an error in STL 2017 from microsoft while iteration directories and files operator++ raises exception
recursive_directory_iterator::operator++: The system cannot find the path specified.
do not use this buggy implementation. use boost instead. I waste much time for it.
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.