3

I have a path such as this:

boost::filesystem::path mypath("c:/test");
boost::filesystem::path mypath1("c:/test/);

I want to make sure that when I convert them to string, both of them appears as :

c:/test/

for example if I do:

cout<<mypath.string()<<endl;
cout<<mypath1.string()<<endl;

both of them print out:

c:/test/

How can I do this in c++ using boost?

1
  • I don't think any of the standard functions in the file system library supports what you are after, it will always tread C:/test as a file and C:/test/ as a directory - until you check it.. Your best bet would be to convert to string and check if it ends with a path separator and if not, add it to the string! Commented Oct 27, 2015 at 14:55

1 Answer 1

1

I don't think there is a builtin function.

You could use this, though:

if ("." != p.filename()) 
   p += fs::path::preferred_separator;

This will not add the separator if the path ends in /.

Optionally, call p.remove_trailing_separator first, but that will also remove any trailing double-slash if it was part of the input (some applications treat this as having significant meaning).

Live On Coliru

#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
#include <iostream>

namespace fs = boost::filesystem;

int main(int argc, char** argv) {
    for (std::string s : boost::make_iterator_range(argv+1, argv+argc)) {
        fs::path p = s;
        //p.remove_trailing_separator();
        if ("." != p.filename())
            p += fs::path::preferred_separator;

        std::cout << "'" << s << "'\t" << p << "\n";
    }
}

Prints (on linux, obviously):

'.' "."
''  "/"
'/' "//"
'/tmp'  "/tmp/"
'/tmp/' "/tmp/"
'/tmp//'    "/tmp//"
'/tmp/.'    "/tmp/."
'/tmp/..'   "/tmp/../"
'/tmp/...'  "/tmp/.../"
'/tmp/aa.txt'   "/tmp/aa.txt/"
'c:\test.txt'   "c:\test.txt/"
Sign up to request clarification or add additional context in comments.

3 Comments

why you excludes "." but not "" ?
@sercxjo Actually, I don't remember. I think "" is just a bad example - it's not a valid path and it would be unsafe to assume it means "/". So I'd rather suggest to input validate that "" is not valid input and always leave a trailing /, including "./". To be completely honest, I think the real problem is that it is pretty unclear why the output format matters to OP (to me /some/path/./ doesn't make more sense than /some/path/.. My examples were chosen to reflect how weird the requirement works out, see the last entries)
@sercxjo Ah. I (and you) should just have tried it out. The comment in the answer explained it: "This will not add the separator if the path ends in /.", compare: coliru.stacked-crooked.com/a/cb04270976fd76f6

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.