c++ - parent_path()带有或不带有斜杠

标签 c++ boost boost-filesystem

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/

相关文章:

c++ - 使用互斥量时出错

c++ - 在 C++ 中声明数组

c++ - TBB 与 C++ 的链接

c++ - 使用 boost::function 通过函数指针调用 C++ 类方法

c++ - boost 文件系统获取权限返回 (509)dec == (1FD)hex。该值不在文档中

c++ - 为什么 boost::filesystem::path 和 std::filesystem::path 缺少 operator+?

c++ - boost::filesystem::unique_path() 如何解决 C++ 中 mkstemp 模拟的需求?

c++ - ubuntu 12.04 中的 gtkmm 3 错误

c++ - 我无法理解 std::istream_iterator 的使用

c++ - `boost::local_time::date_time` 来自 `std::string`