【问题标题】:Determine if some relative directory is part of absolute path using std::filesystem::path使用 std::filesystem::path 确定某个相对目录是否是绝对路径的一部分
【发布时间】:2020-11-17 09:57:37
【问题描述】:

我不知道如何使用 std::filesystem::path 识别绝对路径是否包含一些相对目录,但仍然没有运气。我有以下代码和平:

const std::filesystem::path absolutePath = "/Users/user/Library/Preferences";
const std::filesystem::path relativePath = "Library/Preferences";
bool isSubDir = isSubDirectory(absolutePath, relativePath);

isSubDirectory 在这种情况下应该返回 true。感谢任何帮助。

【问题讨论】:

    标签: c++ path c++17 std-filesystem


    【解决方案1】:

    std::filesystem::path 类为第一个和最后一个元素提供迭代器。所以你可以使用std::search在绝对路径中搜索相对路径:

    #include <algorithm>
    #include <filesystem>
    
    namespace fs = std::filesystem;
    
    bool isSubDirectory(const fs::path& absolutePath, const fs::path& relativePath)
    {
        auto it = std::search(absolutePath.begin(), absolutePath.end(), relativePath.begin(), relativePath.end());
        return it != absolutePath.end();
    }
    

    【讨论】:

    • 谢谢,但我的意思是不存在,我需要确定相对路径是否是绝对路径的一部分。
    • @Oleg 存在误解。检查我更新的答案。
    猜你喜欢
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 2010-10-25
    • 2021-12-23
    • 2012-07-09
    • 2011-04-25
    • 2019-09-09
    • 2015-11-13
    相关资源
    最近更新 更多