温馨提示×

C++相对路径如何转换为绝对路径

c++
小樊
128
2024-07-20 07:52:41
栏目: 编程语言

在C++中,可以使用std::filesystem::canonical()函数来将相对路径转换为绝对路径。以下是一个示例代码:

#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {
    fs::path relativePath = "myFolder/myFile.txt";
    fs::path absolutePath = fs::canonical(relativePath);

    std::cout << "Relative path: " << relativePath << std::endl;
    std::cout << "Absolute path: " << absolutePath << std::endl;

    return 0;
}

在上面的示例中,我们使用fs::canonical()函数将相对路径myFolder/myFile.txt转换为绝对路径。然后将相对路径和绝对路径分别打印出来。

请注意,需要在编译时使用-std=c++17或更高版本的标准来支持std::filesystem库。

0