Boiethios Boiethios - 20 days ago 7
C++ Question

How to list all the files with given extension from directory, using filesystem?

Since

filesystem
exists in experimental part of compilers and will arrive in the newest version of C++, how to list the files with a given extension from a directory using it?

I use VS2015. I do not look for standard way to do this, only under Ms Windows.

Answer

You can use std::experimental::filesystem::directory_iterator and filter manually:

for(const auto& p : fs::directory_iterator("some_directory"))
{
    if(p.path().extension() == ".txt")
    { 
        /* ... */
    }
}

You can create a nice wrapper as follows:

template <typename TF>
void for_files_with_extension(std::string_view dir, std::string_view ext, TF&& f)
{
    for(const auto& p : fs::directory_iterator(dir))
    {
        if(p.path().extension() == ext)
        { 
            f(p);
        }
    }
}

Which can be used like this:

for_files_with_extension("/home/someone/", ".txt", 
    [](const auto& p){ std::cout << "Found text file at " << p << "\n"; });
Comments