Makogan
Makogan

Reputation: 9540

std::filesystem::recursive_directory_iterator with consistent path separation?

I just noticed that std::filesystem::recursive_directory_iterator uses different path separateors (i.e. / vs \) depending on whether it's on Windows or Linux, is there a way to make it return paths with '/' to make it consistent across systems?

This is how I am getting the paths:

for(auto& path: fs::recursive_directory_iterator(dir_path))
{
    // Skip directories in the enumeration.
    if(fs::is_directory(path)) continue;
    string path_str = path.path().string();
}

What I mean is, the contents of path_str will be different between the two OSs (because the separators will be different), I would like them to be the same. I could just replace them on the final string, but that uses more cycles than if I can instruct the stl to use '/' for everything isntead.

Upvotes: 3

Views: 774

Answers (1)

Etienne de Martel
Etienne de Martel

Reputation: 36852

So, your problem has nothing to do with recursive_directory_iterator, which iterates on directory_entry objects, not paths. Your confusion probably stems from the fact that directory entries are implicitly convertible to paths, so you can use them as such.

Your problem is really about path::string(), which, as the documentation states, uses the native format (i.e. with a platform dependent separator). You would get the same problem regardless of how you get your path.

If you want to get / as the directory separator, use path::generic_string() instead to get the path in generic format.

for(auto& dir_entry: fs::recursive_directory_iterator(dir_path))
{
    if(dir_entry.is_directory()) continue;
    string path_str = dir_entry.path().generic_string();
}

Upvotes: 4

Related Questions