How to recursively list a directory using C++17 filesystem library

Note: To find out how to list a directory non-recursively, just replace recursive_directory_iterator by directory_iterator or see our full post How to list a directory using C++17 filesystem library.

To recursively list a directory using the C++17 filesystem library use this snippet:

#include <experimental/filesystem>

using namespace std::experimental::filesystem;

for(const directory_entry& entry : recursive_directory_iterator("my-directory")) {
    const auto& path = entry.path();
    // ...
}

Full example:

#include <iostream>
#include <string>
#include <experimental/filesystem>

using namespace std;
using namespace std::experimental::filesystem;

int main() {
    for(const directory_entry& entry : recursive_directory_iterator("my-directory")) {
        // Is it a file / directory?
        bool isNormalFile = is_regular_file(entry);
        bool isDirectory = is_directory(entry);

        auto path = entry.path();
        // Path: my-directory/test.txt
        string pathString = path.string();

        // Filename: test.txt
        string filenameString = path.filename().string();

        // Extension: txt
        string extensionString = path.extension().string();

        // NOTE: You can also "cout << path" directly
    }
}

Compile like this:

g++ -o filesystem-example filesystem-example.cpp -lstdc++fs

For this directory:

my-directory
├── subdirectory
│   └── subdir-test.txt
└── test.txt

this will list subdirectory , subdirectory/subdir-test.txt and test.txt.