Search code examples
c++stdstd-filesystem

Getting the path of recursively iterated directories relative to the specified entry path


Consider the example in the documentation of std::filesystem::recursive_directory_iterator:

#include <fstream>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
 
int main()
{
    fs::current_path(fs::temp_directory_path());
    fs::create_directories("sandbox/a/b");
    std::ofstream("sandbox/file1.txt");
    fs::create_symlink("a", "sandbox/syma");
    for(auto& p: fs::recursive_directory_iterator("sandbox"))
        std::cout << p.path() << '\n';
    fs::remove_all("sandbox");
}

Possible output:

"sandbox/a"
"sandbox/a/b"
"sandbox/file1.txt"
"sandbox/syma"

I would like to drop from the output the sandbox/ prefix which was specified when constructing the recursive_directory_iterator, eg:

"a"
"a/b"
"file1.txt"
"syma"

I browsed the documentation but I could not find anything relevant.

It is not a big deal to do a bit of string processing, but I do not like having to introduce a somewhat lower level code, doing a round trip from paths to strings. Is this actually the only shot?


Solution

  • You can use std::filesystem::relative, this might look like:

    std::cout << fs::relative(p.path(), "sandbox") << '\n';