c++

C++ getcwd如何处理相对路径

小樊
84
2024-11-27 15:15:15
栏目: 编程语言

getcwd() 函数用于获取当前工作目录的绝对路径

#include <iostream>
#include <cstdio>
#include <cstring>

int main() {
    char cwd[PATH_MAX];
    if (getcwd(cwd, sizeof(cwd)) != nullptr) {
        std::cout << "Current working directory: " << cwd << std::endl;
    } else {
        perror("getcwd() error");
        return 1;
    }
    return 0;
}

如果你需要将相对路径转换为绝对路径,可以使用 realpath() 函数。这是一个示例:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <limits.h>

int main() {
    char relative_path[] = "./test";
    char absolute_path[PATH_MAX];

    // 将相对路径转换为绝对路径
    if (realpath(relative_path, absolute_path) != nullptr) {
        std::cout << "Absolute path: " << absolute_path << std::endl;
    } else {
        perror("realpath() error");
        return 1;
    }
    return 0;
}

在这个示例中,realpath() 函数接收一个相对路径(./test),并将其转换为绝对路径。如果转换成功,realpath() 返回指向绝对路径的指针;否则,返回 nullptr

0
看了该问题的人还看了