c++boostboost-filesystem

parent_path() with or without trailing slash


As explained in the documentation, the expected output of the following is:

boost::filesystem::path filePath1 = "/home/user/";
cout << filePath1.parent_path() << endl; // outputs "/home/user"

boost::filesystem::path filePath2 = "/home/user";
cout << filePath2.parent_path() << endl; // outputs "/home"

The question is, how do you deal with this? That is, if I accept a path as an argument, I don't want the user to care whether or not it should have a trailing slash. It seems like the easiest thing to do would be to append a trailing slash, then call parent_path() TWICE to get the parent path of "/home" that I want:

boost::filesystem::path filePath1 = "/home/user/";
filePath1 /= "/";
cout << filePath1.parent_path().parent_path() << endl; // outputs "/home"

boost::filesystem::path filePath2 = "/home/user";
filePath2 /= "/";
cout << filePath2.parent_path().parent_path() << endl; // outputs "/home"

but that just seems ridiculous. Is there a better way to handle this within the framework?


Solution

  • There is a (undocumented?) member function: path& path::remove_trailing_separator();

    I tried this and it worked for me on Windows using boost 1.60.0:

    boost::filesystem::path filePath1 = "/home/user/";
    cout << filePath1.parent_path() << endl; // outputs "/home/user"
    cout << filePath1.remove_trailing_separator().parent_path() << endl; // outputs "/home"
    
    boost::filesystem::path filePath2 = "/home/user";
    cout << filePath2.parent_path() << endl; // outputs "/home"
    cout << filePath2.remove_trailing_separator().parent_path() << endl; // outputs "/home"