c语言获取程序运行目录
作者:野牛程序员:2024-07-02 10:40:39C语言阅读 3090
c语言获取程序运行目录
在C语言中,可以使用getcwd函数来获取程序的当前工作目录。这个函数定义在unistd.h头文件中。以下是一个示例代码:
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
int main() {
char currentDirectory[PATH_MAX];
// 获取当前工作目录
if (getcwd(currentDirectory, sizeof(currentDirectory)) != NULL) {
printf("当前目录: %s\n", currentDirectory);
} else {
perror("getcwd() 错误");
}
return 0;
}上述代码中,getcwd函数用于获取当前工作目录,并将结果存储在currentDirectory数组中。如果获取成功,会打印当前目录;如果失败,会输出错误信息。
获取程序所在目录
获取程序所在目录(即可执行文件的路径)在不同的操作系统上方法有所不同。以下是一些常用的方式:
在Linux上
可以读取/proc/self/exe符号链接:
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
int main() {
char exePath[PATH_MAX];
// 获取可执行文件的路径
ssize_t len = readlink("/proc/self/exe", exePath, sizeof(exePath) - 1);
if (len != -1) {
exePath[len] = '\0';
printf("可执行文件路径: %s\n", exePath);
} else {
perror("readlink 错误");
}
return 0;
}在Windows上
可以使用GetModuleFileName函数:
#include <stdio.h>
#include <windows.h>
int main() {
char exePath[MAX_PATH];
// 获取可执行文件的路径
if (GetModuleFileName(NULL, exePath, MAX_PATH) != 0) {
printf("可执行文件路径: %s\n", exePath);
} else {
printf("获取路径失败,错误代码: %lu\n", GetLastError());
}
return 0;
}以上代码在不同操作系统上分别演示了如何获取程序的当前工作目录和可执行文件的路径。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:C#中如何获取当前目录和上级目录
- 下一篇:php通用获取目录文件数
