Search code examples
c++boostboost-filesystemhidden-files

How do I ignore hidden files (and files in hidden directories) with Boost Filesystem?


I am iterating through all files in a directory recursively using the following:

try
{
    for ( bf::recursive_directory_iterator end, dir("./");
          dir != end; ++dir )
    {
       const bf::path &p = dir->path();
       if(bf::is_regular_file(p))
       {
           std::cout << "File found: " << p.string() << std::endl;
       }
    }
} catch (const bf::filesystem_error& ex) {
    std::cerr << ex.what() << '\n';
}

But this includes hidden files and files in hidden directories.

How do I filter out these files? If needed I can limit myself to platforms where hidden files and directories begin with the '.' character.


Solution

  • Unfortunately there doesn't seem to be a cross-platform way of handling "hidden". The following works on Unix-like platforms:

    First define:

    bool isHidden(const bf::path &p)
    {
        bf::path::string_type name = p.filename();
        if(name != ".." &&
           name != "."  &&
           name[0] == '.')
        {
           return true;
        }
    
        return false;
    }
    

    Then traversing the files becomes:

    try
    {
        for ( bf::recursive_directory_iterator end, dir("./");
               dir != end; ++dir)
        {
           const bf::path &p = dir->path();
    
           //Hidden directory, don't recurse into it
           if(bf::is_directory(p) && isHidden(p))
           {
               dir.no_push();
               continue;
           }
    
           if(bf::is_regular_file(p) && !isHidden(p))
           {
               std::cout << "File found: " << p.string() << std::endl;
           }
        }
    } catch (const bf::filesystem_error& ex) {
        std::cerr << ex.what() << '\n';
    }