Shout
Shout

Reputation: 683

How to implement recursive directories and files listing using std::filesystem?

I want to implement recursive directories and files listing on my own. I do not want to use

std::filesystem::recursive_directory_iterator

I tried this code:

void TraverseDirectory(const std::string& rootDirectory)
{
    //Go thru the root directory
    for(const auto& entry : std::filesystem::directory_iterator(rootDirectory)) {
        std::string filenameStr = entry.path().filename().string();
        //if the first found entry is directory go thru it
        if(entry.is_directory()) {
            std::cout << "Dir: " << filenameStr << '\n';
            TraverseDirectory(filenameStr);
        } 
        //print file name
        else if(entry.is_regular_file()) {
            std::cout << "file: " << filenameStr << '\n';
        }
    }
}

int main()
{
    TraverseDirectory("testdir");
}

but it gives me this error when the main loop enters TraverseDirectory(filenameStr);:

enter image description here

How can I iterate over directories and its files without the error shown above?

Upvotes: 2

Views: 557

Answers (1)

vtronko
vtronko

Reputation: 488

std::filesystem::path::filename

Returns the generic-format filename component of the path.

Equivalent to relative_path().empty() ? path() : *--end().

This means, that for actual path /foo/bar/42.txt you get 42.txt return. Now, here in

if(entry.is_directory()) {
   std::cout << "Dir: " << filenameStr << '\n';
   TraverseDirectory(filenameStr);
}

Your recursive call receives only filename part of path, hence tries to walk into bar, instead of foo/bar for example.

So you better off changing that to

TraverseDirectory(entry.path());

Upvotes: 2

Related Questions