问题描述
如文档,则以下内容的预期输出为:
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"
问题是,您如何处理?也就是说,如果我接受路径作为参数,则我不希望用户关心路径是否应带有斜杠.似乎最简单的方法是在末尾添加一个斜杠,然后调用parent_path()
TWICE以获取我想要的"/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?
推荐答案
有一个(未记录?)成员函数:path& path::remove_trailing_separator();
There is a (undocumented?) member function: path& path::remove_trailing_separator();
我尝试了这个,它在Windows上使用boost 1.60.0
起作用了:
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"
这篇关于parent_path()带有或不带有斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!