Bootstrap

c++17 判断文件路径是否为目录子路径

之所以要写这个代码,是因为大模型给的代码有bug,于是把有bug的代码和修改后的代码拿出来对比,避免这个bug。

需求如下:

linux系统,给定两个路径,判断一个路径是否在另外一个路径下,用c++17

bug的代码如下:

// !!!注意此代码有bug,仅作示范
#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

bool isSubPath(const fs::path& basePath, const fs::path& path) {
    // 将路径标准化,消除路径中的相对路径符号
    fs::path normalizedBasePath = fs::canonical(basePath);
    fs::path normalizedPath = fs::canonical(path);

    // 检查路径是否是子路径
    return normalizedPath.string().find(normalizedBasePath.string()) == 0;
}

int main() {
    fs::path basePath = "/mnt/mount_data2/jishu";
    fs::path path = "/mnt/mount_data2/jishufenxiang/test";

    if (isSubPath(basePath, path)) {
        std::cout << path << " is a subpath of " << basePath << std::endl;
    } else {
        std::cout << path << " is NOT a subpath of " << basePath << std::endl;
    }

    return 0;
}

打印信息如下(错误示范):

"/mnt/mount_data2/jishufenxiang/test" is a subpath of "/mnt/mount_data2/jishu"

可以看下basePath和path,如果只判断字符串的话,也会被识别成子路径

修改后正确大代码如下,可以正确识别

// 正确的代码!!!
#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

bool isSubPath(const fs::path& basePath, const fs::path& path) {
    // 规范化路径
    auto normalizedBasePath = fs::canonical(basePath);
    auto normalizedPath = fs::canonical(path);

    // 检查是否为子路径
    return normalizedPath.has_relative_path() && normalizedPath.parent_path() == normalizedBasePath;
}

int main() {
    fs::path basePath = "/mnt/mount_data2/jishufenxiang";
    fs::path path = "/mnt/mount_data2/jishufenxiang/test";

    if (isSubPath(basePath, path)) {
        std::cout << path << " 是 " << basePath << " 的子路径" << std::endl;
    } else {
        std::cout << path << " 不是 " << basePath << " 的子路径" << std::endl;
    }

    return 0;
}
"/mnt/mount_data2/jishufenxiang/test" 是 "/mnt/mount_data2/jishufenxiang" 的子路径

如果传入参数

fs::path basePath = "/mnt/mount_data2/jishu";
fs::path path = "/mnt/mount_data2/jishufenxiang/test";

打印如下:

"/mnt/mount_data2/jishufenxiang/test" 不是 "/mnt/mount_data2/jishu" 的子路径

;