在 C++ 中,可以使用文件系统库中的 parent_path() 函数来获取给定路径的父路径。

例如:

#include <filesystem>
#include <iostream>

int main() {
    std::filesystem::path path("/home/user/Documents/file.txt");
    std::filesystem::path parent = path.parent_path();

    std::cout << "Parent path: " << parent << std::endl;

    return 0;
}

输出:

Parent path: "/home/user/Documents"

注意,要在编译时链接文件系统库,例如使用以下命令编译:

g++ -std=c++17 -lstdc++fs main.cpp -o main
C++ 获取父路径:使用 `parent_path()` 函数

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

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