1

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

NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277
  • Although windows supports either / or \ in most file operations I expect this is a bug in the implementation from microsoft. – drescherjm Sep 16 '19 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. – Hans Passant Sep 16 '19 at 12:59
  • it's broken like this since MS-DOS, not using the normal slash... causing all this pain decades later... – Ped7g Sep 16 '19 at 13:23
  • 2
    Can you provide a [mre]? That would help provide context. – L. F. Sep 16 '19 at 13:41

1 Answers1

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 });
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108