'directory_iterator skip over inaccessible files folders Windows

I am trying to iterate over all the folders in my C:\ directory, and ONLY in the C:\ directory. Not in any subfolders. My current problem is that it includes inaccessible files and folders like swapfile.sys or System Volume Information when iterating. How can I check the flags or whatnot to exclude such objects?

for (const auto& entry : std::filesystem::directory_iterator(dir))    
{
    
    // Have the if() check here to see if it's accessible
        directory.emplace_back(f);
}


Solution 1:[1]

If the iteration is failing due to trying to access an inaccessible item, you can specify the skip_permission_denied flag in the iterator's constructor, eg:

for (const auto& entry : std::filesystem::directory_iterator(dir, std::filesystem::directory_options::skip_permission_denied))    
{
    directory.emplace_back(f);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Remy Lebeau