1

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?

DarioP
  • 5,377
  • 1
  • 33
  • 52
  • 1
    Could you use `std::filesystem::relative`? Example for inside the for loop: `const auto base_path = fs::current_path().append("sandbox"); const auto relative_path = fs::relative(p.path(), base_path); std::cout << relative_path << '\n';`. – Lily Nov 23 '20 at 13:30
  • 1
    @Lily `relative` is a great advice. It can be applied in a very straightforward way: `std::cout << fs::relative(p.path(), "sandbox") << '\n';` is all I needed. If you make that an answer I would be happy to upvote and accept. – DarioP Nov 23 '20 at 15:43
  • I have now posted it as an answer and using the shorter syntax you found – Lily Nov 23 '20 at 16:59

1 Answers1

1

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

std::cout << fs::relative(p.path(), "sandbox") << '\n';
Lily
  • 1,386
  • 2
  • 13
  • 16