【问题标题】:Get the absolute path from std::filesystem::path c++从 std::filesystem::path c++ 获取绝对路径
【发布时间】:2020-07-04 11:42:12
【问题描述】:

我有这段代码

auto path = std::filesystem::path("/root/home/../opt/.");

我曾尝试过 std::filesystem::absolute(),但后来意识到这不是我想要的结果

我的问题是如何将该相对路径转换为绝对路径,以便结果为"/root/opt/"

我在 Debian g++-9 上使用 c++17

【问题讨论】:

  • 您想要规范路径 (link)。

标签: c++ c++17 filepath c++-standard-library std-filesystem


【解决方案1】:

使用std::filesystem::canonical将路径变成绝对路径,去掉所有..reference):

auto path = std::filesystem::canonical("/root/home/../opt/.");

给你:

"/root/opt"

【讨论】:

    【解决方案2】:

    你也可以使用from这个函数。

     std::cout << std::filesystem::path("/root/home/../opt/.").lexically_normal()    << std::endl;
    

    【讨论】:

    • 值得注意的是:与其他答案 (canonical) 不同,lexically_normal 方法不会尝试解析符号链接,实际上根本不会执行任何文件系统操作。它只是一种字符串操作方法,因此得名。根据具体情况,这可能是也可能不是您想要的。
    猜你喜欢
    • 2012-09-20
    • 1970-01-01
    • 2019-11-06
    • 2019-08-16
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 2022-06-10
    • 2012-08-27
    相关资源
    最近更新 更多