【问题标题】:Getting the path of recursively iterated directories relative to the specified entry path获取递归迭代目录相对于指定入口路径的路径
【发布时间】:2020-11-23 11:50:44
【问题描述】:

考虑the documentationstd::filesystem::recursive_directory_iterator 中的示例:

#include <fstream>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
 
int main()
{
    fs::current_path(fs::temp_directory_path());
    fs::create_directories("sandbox/a/b");
    std::ofstream("sandbox/file1.txt");
    fs::create_symlink("a", "sandbox/syma");
    for(auto& p: fs::recursive_directory_iterator("sandbox"))
        std::cout << p.path() << '\n';
    fs::remove_all("sandbox");
}

可能的输出:

"sandbox/a"
"sandbox/a/b"
"sandbox/file1.txt"
"sandbox/syma"

我想从输出中删除构造 recursive_directory_iterator 时指定的 sandbox/ 前缀,例如:

"a"
"a/b"
"file1.txt"
"syma"

我浏览了文档,但找不到任何相关内容。

做一点字符串处理没什么大不了的,但我不喜欢引入一些较低级别的代码,从路径到字符串进行往返。这真的是唯一的镜头吗?

【问题讨论】:

  • 你能用std::filesystem::relative吗? for 循环内部的示例:const auto base_path = fs::current_path().append("sandbox"); const auto relative_path = fs::relative(p.path(), base_path); std::cout &lt;&lt; relative_path &lt;&lt; '\n';.
  • @Lily relative 是一个很好的建议。它可以以非常直接的方式应用:std::cout &lt;&lt; fs::relative(p.path(), "sandbox") &lt;&lt; '\n'; 就是我所需要的。如果您做出这样的回答,我将很乐意支持并接受。
  • 我现在已将其发布为答案并使用您找到的较短语法

标签: c++ std std-filesystem


【解决方案1】:

你可以使用std::filesystem::relative,这可能看起来像:

std::cout << fs::relative(p.path(), "sandbox") << '\n';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 2015-09-25
    • 2012-07-02
    相关资源
    最近更新 更多