I need to recursively search files into one directory and its subdirectory but I want to exclude one path (with its files and subdirectory) from the search.
I'm using std::experimental::filesystem::recursive_directory_iterator and pop() modifier but it doesn't work. Where I'm wrong?
void search(const char* pathToSearch,const char* pathToExclude){
std::experimental::filesystem::recursive_directory_iterator iterator(pathToSearch);
for (auto& p : iterator) {
if (p.path() == std::experimental::filesystem::directory_entry(pathToExclude).path()) iterator.pop();
if (fs::is_directory(p)) continue; //exclude directory from output
else std::cout << p << std::endl;
}
}
First, the range-based for loop operates on a hidden copy of iterator, not iterator itself. If you need to manipulate the iterator being used for iteration, you need the regular for:
for(decltype(iterator) end; iterator != end; ++iterator) {
// ...
}
Second, pop means "go up one level", but when you compared iterator->path() to your excluded path, your iteration hasn't descended into the directory so pop won't do the right thing. Instead, use disable_recursion_pending.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With