2

I have a C++ program where I use recursive iterator to go through folder that I provide as an argument to program.

Problem is that when I call .string on paths I get I get mixed \ and / in the path. Using .generic_string fixes this problem, but I wonder if this is a bug in VS2019 or allowed behavior.

To give some examples: I give a/b as input to my program.

When I iterate over all the files and print them using .string I get

a/b\c\bla.txt

a/b\d\lol.txt

and when I use .generic_string I get

a/b/c/bla.txt

a/b/d/lol.txt

4
  • Although windows supports either / or \ in most file operations I expect this is a bug in the implementation from microsoft. Commented Sep 16, 2019 at 12:58
  • 2
    Use Windows sensibilities and pass a\b to your program. It otherwise doesn't matter at all, the OS handles either. Commented Sep 16, 2019 at 12:59
  • it's broken like this since MS-DOS, not using the normal slash... causing all this pain decades later... Commented Sep 16, 2019 at 13:23
  • 2
    Can you provide a minimal reproducible example? That would help provide context. Commented Sep 16, 2019 at 13:41

1 Answer 1

2

Make sure that you convert the argument given by the user to an absolute path before using it with the directory iterator, otherwise, it'll display whatever the user supplied.

Example:

#include <filesystem>
#include <iostream>
#include <string_view>
#include <vector>

namespace fs = std::filesystem;

int ftw(const fs::path& p) {
    // give an absolute path to the iterator
    for (const auto& f : fs::recursive_directory_iterator(fs::absolute(p))) {
        std::cout << f.path().string() << "\n";
    }
    return 0;
}

int cppmain(const std::string_view program, std::vector<std::string_view> args) {
    for (const auto& arg : args)
        ftw(arg);
    return 0;
}

int main(int argc, char* argv[]) {
    return cppmain(argv[0], { argv + 1, argv + argc });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.