Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 531
Ron Avatar asked Sep 13 '18 16:09

Ron


1 Answers

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';
}
like image 87
Ron Avatar answered Nov 15 '22 12:11

Ron