Home > front end >  directory_iterator skip over inaccessible files folders Windows
directory_iterator skip over inaccessible files folders Windows

Time:02-02

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);
}

CodePudding user response:

You can use fs::status(entry).permissions() to get the permissions of the current entry and choose whether to skip it according to its flag value.

for (const auto& entry : fs::directory_iterator(dir)) {
  auto p = fs::status(entry).permissions();
  if ((p & fs::perms::owner_read) != fs::perms::none)
    directory.emplace_back(f);
}

CodePudding user response:

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);
}
  •  Tags:  
  • Related