1、用 getcwd() 函数(推荐)
最常用、标准、跨平台的方法之一(POSIX 标准,Unix/Linux/macOS 支持)。
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
int main() {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("当前工作目录是: %s\n", cwd);
} else {
perror("getcwd 错误");
return 1;
}
return 0;
}
getcwd(char *buf, size_t size)
将当前工作目录的路径写入 buf
。PATH_MAX
表示系统定义的路径最大长度,来自 。若失败,getcwd()
返回 NULL
,可用 perror()
输出错误原因。
2、使用 get_current_dir_name()(仅限 GNU/Linux)
get_current_dir_name()
是 GNU 扩展,不是标准 POSIX,不可移植到 macOS 或 Windows。返回值需使用 free()
手动释放。
#include <stdio.h>
#include <stdlib.h>
int main() {
char *cwd = get_current_dir_name();
if (cwd != NULL) {
printf("当前工作目录是: %s\n", cwd);
free(cwd);
} else {
perror("get_current_dir_name 错误");
}
return 0;
}
3、Windows 系统使用 GetCurrentDirectory()
在 Windows 上编写 C 程序,可以使用 WinAPI。
#include <windows.h>
#include <stdio.h>
int main() {
char buffer[MAX_PATH];
DWORD length = GetCurrentDirectoryA(MAX_PATH, buffer);
if (length > 0 && length <= MAX_PATH) {
printf("当前工作目录是: %s\n", buffer);
} else {
printf("获取目录失败\n");
}
return 0;
}