如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()
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"
但这似乎很荒谬。在框架中是否有更好的方法来处理此问题?
最佳答案
有一个(未记录?)成员函数: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"
关于c++ - parent_path()带有或不带有斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62209378/