如何更直观地遍历C++17的filesystem::path以向上跳转目录?
C++17 filesystem::path 向上跳转多级目录的替代方法
问题描述
我希望使用C++17的<filesystem>头文件让路径向上跳转2级目录,当前通过多次调用parent_path()实现,代码如下:
auto mpath = std::filesystem::path(SDL_GetBasePath()); std::cout << mpath.parent_path().parent_path().parent_path() << std::endl;
请问除了重复调用parent_path()外,是否存在更直观的遍历filesystem::path的方法?
解决方案
这里提供几种更直观的实现方式:
1. 直接拼接相对路径
最简洁的方式是直接拼接../表示向上跳转,代码可读性极强,一眼就能看出跳转层级:
#include <filesystem> #include <iostream> namespace fs = std::filesystem; int main() { auto mpath = fs::path(SDL_GetBasePath()); // 向上跳转2级,lexically_normal()用于规范化路径,消除../和对应组件 auto up_two = (mpath / "../..").lexically_normal(); std::cout << up_two << std::endl; return 0; }
- 注意:若不调用
lexically_normal(),路径中会保留../组件;调用后会直接计算出实际的上级路径,避免路径冗余。
2. 封装工具函数
如果需要频繁向上跳转指定层级,封装可复用函数能避免重复代码,同时加入边界判断更健壮:
#include <filesystem> #include <iostream> namespace fs = std::filesystem; // 向上跳转指定层级,已到根目录则停止 fs::path jump_up(fs::path current_path, size_t levels) { for (size_t i = 0; i < levels; ++i) { if (current_path.is_root_directory()) { break; // 根目录无法继续向上跳转 } current_path = current_path.parent_path(); } return current_path; } int main() { auto mpath = fs::path(SDL_GetBasePath()); auto up_two = jump_up(mpath, 2); std::cout << up_two << std::endl; return 0; }
3. 利用路径迭代器构造新路径
filesystem::path支持迭代器遍历路径组件,可通过截取前总组件数 - N个组件构建上级路径,适合需要对路径组件做复杂操作的场景:
#include <filesystem> #include <iostream> #include <vector> namespace fs = std::filesystem; int main() { auto mpath = fs::path(SDL_GetBasePath()); std::vector<fs::path> components(mpath.begin(), mpath.end()); // 确保有足够层级可跳转,避免越界 constexpr size_t jump_levels = 2; if (components.size() > jump_levels) { components.resize(components.size() - jump_levels); } fs::path up_two; for (const auto& comp : components) { up_two /= comp; } std::cout << up_two << std::endl; return 0; }
内容的提问来源于stack exchange,提问作者Lampros
相关产品推荐
相关产品推荐

