Ron
Ron

Reputation: 15501

The std::filesystem::recursive_directory_iterator exception

The following function:

void foo(const std::string& dir)
{
    for (auto& el : std::filesystem::recursive_directory_iterator(dir)) {
            std::cout << el.path() << '\n';
    }
}

when used in:

int main()
{
    std::string p = "C:\\";
    foo(p);
}

raises an exception when it reaches a certain folder (I assume) on Windows 10. The code is compiled on VS 2017 with C++17 support. The exception message is:

recursive_directory_iterator::operator++: The system cannot find the path specified.

The same behavior occurs when using the std::filesystem::directory_iterator too. Why is it raising an exception on that particular folder?

Upvotes: 6

Views: 6833

Answers (2)

Decaf Sux
Decaf Sux

Reputation: 367

I just got this error on Windows 10 on a folder entry.

The entry was corrupt and it was not possible to read or delete that folder in windows at all. I could however rename the folder, but in the end I had to wipe the hard drive because not even Windows (or any commands/repair tools) could fix the issue.

So in my case I would say that it was an appropriate exception (as expected).

Upvotes: 0

Ron
Ron

Reputation: 15501

Apparently, exception is raised when the OS denies a permission to access one of the folders.

The workaround is to utilize the appropriate recursive directory iterator constructor overload (4th one) and supply the skip_permission_denied parameter:

for (auto& el : std::filesystem::recursive_directory_iterator(dir, std::filesystem::directory_options::skip_permission_denied)) {
    std::cout << el.path() << '\n';
}

Upvotes: 10

Related Questions