如 documentation 中所述,以下的预期输出是:
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"
问题是,你如何处理这个问题?也就是说,如果我接受一个路径作为参数,我不希望用户关心它是否应该有尾部斜线。看起来最简单的做法是在尾部附加一个斜杠,然后调用 parent_path()
两次以获得我想要的“/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"
但这看起来很荒谬。有没有更好的方法在框架内处理这个问题?
最佳答案
您可以在 C++17 中使用 std::filesystem::canonical
:
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
关于c++ - parent_path() 带或不带斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36941934/