3

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;
    }
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
gimiki
  • 83
  • 8

1 Answers1

3

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.

T.C.
  • 133,968
  • 17
  • 288
  • 421