parent_path()带或不带斜杠

Dav*_*ria 4 c++ boost boost-filesystem

文档中所述,以下预期输出为:

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"
Run Code Online (Sandbox Code Playgroud)

问题是,你如何处理这个问题?也就是说,如果我接受一个路径作为参数,我不希望用户关心它是否应该有一个尾部斜杠.看起来最简单的事情就是附加一个尾部斜杠,然后调用parent_path()TWICE来获取我想要的"/ home"的父路径:

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"
Run Code Online (Sandbox Code Playgroud)

但这看起来很荒谬.在框架内有更好的方法来处理这个问题吗?

小智 8

You can use std::filesystem::canonical with C++17:

namespace fs = std::filesystem;

fs::path tmp = "c:\\temp\\";

tmp = fs::canonical(tmp); // will remove slash

fs::path dir_name = tmp.filename(); // will get temp
Run Code Online (Sandbox Code Playgroud)

  • 需要注意的是路径必须已经存在 (3认同)

Wur*_*och 7

有一个(未记录的?)成员函数 path& path::remove_trailing_separator();

我试过这个,它在Windows上使用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"
Run Code Online (Sandbox Code Playgroud)

  • 有趣的是,这不处理多个尾随分隔符。即“/home/user//”.remove_trailing_separator().parent_path() 返回“/home/user” (2认同)