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
。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:C++相对路径如何处理循环引用