以下是一个 C++ 函数,它将给定路径的上一级路径返回为字符串:

#include <iostream>
#include <string>

std::string getParentPath(std::string path)
{
    // 查找最后一个目录分隔符的位置
    size_t lastSlashIndex = path.find_last_of("/\");
    if (lastSlashIndex == std::string::npos) {
        // 没有目录分隔符,父路径为当前目录
        return ".";
    }
    // 删除任何尾部目录分隔符
    while (lastSlashIndex > 0 && path[lastSlashIndex - 1] == "/\") {
        lastSlashIndex--;
    }
    // 查找前一个目录分隔符的位置
    size_t previousSlashIndex = path.find_last_of("/\", lastSlashIndex - 1);
    if (previousSlashIndex == std::string::npos) {
        // 没有前一个目录分隔符,父路径为根目录
        return "/";
    }
    // 提取父路径
    return path.substr(0, previousSlashIndex);
}

int main()
{
    std::string path = "/usr/local/bin";
    std::cout << getParentPath(path) << std::endl; // 输出: /usr/local

    path = "C:\Program Files (x86)\Mozilla Firefox\firefox.exe";
    std::cout << getParentPath(path) << std::endl; // 输出: C:\Program Files (x86)\Mozilla Firefox

    path = "/var/log/";
    std::cout << getParentPath(path) << std::endl; // 输出: /var

    path = "/root";
    std::cout << getParentPath(path) << std::endl; // 输出: /

    path = "file.txt";
    std::cout << getParentPath(path) << std::endl; // 输出: .
}

该函数首先查找路径中最后一个目录分隔符的位置。如果找不到目录分隔符,则假定父路径为当前目录,返回'。'。如果找到了目录分隔符,则需要删除任何尾部目录分隔符。然后,函数将查找前一个目录分隔符的位置。如果找不到前一个目录分隔符,则假定父路径为根目录,返回'/'。否则,函数将提取父路径并返回它。

C++ 获取父路径函数实现

原文地址: https://www.cveoy.top/t/topic/nnqc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录