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() 两次以获得我想要的“/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/

相关文章:

c++ - 如何检查路径是否指向可执行文件?

c++ - CMake无法链接外部库

c++ - 共享库有一些问题

c++ - 在 boost::signals 中, 'slot_type' 和 'slot_function_type' 有什么区别?

c++ - std::lock 的友元函数定义和替代 boost 函数

C++/Boost 文件系统 - 检测到 '_MSC_VER' 不匹配 : value '1700' doesn't match value '1600'

c++ - C++ Windows 服务是否比 .Net Windows 服务更稳定?

c++ - 如何使用 Boost::Geometry _union 与整数

c++ - 编译器独立的类名

C++:提升文件系统以返回早于特定时间的文件列表