C++10 获取路径父目录:使用 filesystem 库

在 C++10 中,可以使用 filesystem 库来获取路径的父目录。

下面是一个示例代码:

#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {
    fs::path filePath = '/path/to/file.txt';
    fs::path parentPath = filePath.parent_path();

    std::cout << 'Parent directory: ' << parentPath << std::endl;

    return 0;
}

在上面的代码中,filePath 表示要获取父目录的路径,parentPath 表示父目录的路径。通过调用 parent_path() 函数,可以获取到路径的父目录。

在这个示例中,输出结果将会是 /path/to,表示文件 file.txt 的父目录。

需要注意的是,在使用 filesystem 库之前,需要确保编译器支持 C++17 标准,并链接对应的库。在使用 GCC 编译器时,需要加上 -lstdc++fs 选项。


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

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