To familiarize myself with <filesystem>
, I wrote a simple recursive function that walks a directory tree:
#include <filesystem>
namespace fs = std::tr2::sys;
const fs::directory_iterator fs_end;
void walk(fs::path root)
{
std::cout << "ENTERING " << root << '\n';
for (auto it = fs::directory_iterator(root); it != fs_end; ++it)
{
if (is_directory(it->status()))
{
walk(it->path());
}
else
{
std::cout << it->path() << " is not a directory\n";
}
}
std::cout << "LEAVING " << root << '\n';
}
int main()
{
walk("d:/a");
}
Unfortunately, this will only visit the immediate directories inside the directory specified in main
. The subdirectories are not visited. To illustrate, I made a very simple directory structure:
The output of the program is as follows:
ENTERING d:/a
ENTERING b
LEAVING b
ENTERING c
LEAVING c
LEAVING d:/a
As you can see, d is not visited. Apparently, the for loop is run zero times inside c. Why?
From the output it looks like
it->path()
is giving you the relative path, not the absolute path. While iterating, your current directory does not change, so trying to iterate over a directory with path 'b' or 'c' won't work and no subdirectories will be found in that non-existent directory. In your for-loop, try the following recursive call:Now, when your program examines directory c, it should output: