1、使用 argv[0] 和 realpath()(Linux/Unix 类系统)
在 Linux/Unix 系统中,程序的路径通常可以通过 argv[0]
获取,该参数包含了程序启动时传递的路径。为了获取程序所在目录,可以使用 realpath()
函数将路径解析成绝对路径。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <libgen.h> // dirname
int main(int argc, char *argv[]) {
char path[1024];
char *real_path;
// 获取 argv[0] 的路径
real_path = realpath(argv[0], path);
if (real_path != NULL) {
// 获取目录部分
char *dir = dirname(path);
printf("Program is running from: %s\n", dir);
} else {
perror("Error resolving real path");
}
return 0;
}
2、使用 GetModuleFileName()(Windows 系统)
在 Windows 系统中,可以使用 GetModuleFileName()
来获取当前程序的路径。
#include <stdio.h>
#include <windows.h>
int main() {
char path[MAX_PATH];
DWORD result = GetModuleFileName(NULL, path, MAX_PATH);
if (result > 0) {
// 获取目录部分
char *dir = path;
for (int i = strlen(path) - 1; i >= 0; i--) {
if (path[i] == '\\') {
path[i] = '\0'; // 将路径分隔符替换为字符串结束符
break;
}
}
printf("Program is running from: %s\n", path);
} else {
printf("Failed to get module file name\n");
}
return 0;
}
3、使用 getcwd()(获取当前工作目录,适用于所有平台)
如只需要当前工作目录(即程序启动时所在的目录,而不是程序的实际路径),可以使用 getcwd()
来获取。
#include <stdio.h>
#include <unistd.h>
int main() {
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("Current working directory: %s\n", cwd);
} else {
perror("getcwd failed");
}
return 0;
}
4、使用 __FILE__ 宏
__FILE__
是一个预定义宏,它包含了源文件的路径,可以通过它来获取当前源代码文件所在的路径。
#include <stdio.h>
int main() {
printf("Current file path: %s\n", __FILE__);
return 0;
}