如何在不同平台上获取 C/C++ 程序的执行目录?
在 C/C++ 程序中,获取执行目录(即当前程序所在的目录)的方法会因操作系统而异。以下是如何在不同平台上获取执行目录的几种常用方法。
1. 在 Linux 和 Unix 系统上
在 Linux 或 Unix 系统中,可以使用 readlink 函数来获取程序的执行目录。具体来说,/proc/self/exe 是一个指向当前执行程序的符号链接,通过读取它可以获得程序的绝对路径。
示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <limits.h>
int main() {
char path[PATH_MAX];
ssize_t len = readlink("/proc/self/exe", path, sizeof(path) - 1);
if (len == -1) {
perror("readlink");
return 1;
}
path[len] = '\0'; // Null-terminate the string
char *dir = dirname(path); // Get the directory part of the path
printf("Current execution directory: %s\n", dir);
return 0;
}
readlink("/proc/self/exe", ...)获取当前可执行文件的路径。dirname(path)用于获取路径的目录部分。
2. 在 Windows 系统上
在 Windows 系统中,可以使用 GetModuleFileName 函数来获取程序的完整路径,然后通过字符串操作获取目录部分。
示例代码:
#include <stdio.h>
#include <windows.h>
#include <string.h>
int main() {
char path[MAX_PATH];
DWORD length = GetModuleFileName(NULL, path, MAX_PATH);
if (length == 0) {
printf("Error getting path\n");
return 1;
}
// Find the last backslash in the path and replace it with a null character
char *dir = strrchr(path, '\\');
if (dir) {
*dir = '\0'; // Null-terminate the path at the last backslash
}
printf("Current execution directory: %s\n", path);
return 0;
}
GetModuleFileName(NULL, ...)获取当前执行文件的完整路径。strrchr(path, '\\')用于查找路径中的最后一个反斜杠(\),然后替换它为字符串的终止符(\0)来获取目录部分。
3. 在 macOS 和 Linux 上使用 realpath
在 macOS 和 Linux 系统上,可以使用 realpath 函数获取程序的实际路径,这对于处理符号链接特别有用。
示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
char path[PATH_MAX];
if (realpath("/proc/self/exe", path) == NULL) {
perror("realpath");
return 1;
}
char *dir = dirname(path); // Get the directory part of the path
printf("Current execution directory: %s\n", dir);
return 0;
}
realpath("/proc/self/exe", ...)获取程序的绝对路径。
4. 使用标准库(跨平台)
在现代 C++ 中,你也可以使用 std::filesystem(从 C++17 开始)来获取当前执行目录。它是一个跨平台的解决方案。
示例代码:
#include <iostream>
#include <filesystem>
int main() {
std::filesystem::path exePath = std::filesystem::current_path(); // 获取当前路径
std::cout << "Current execution directory: " << exePath << std::endl;
return 0;
}
std::filesystem::current_path()返回当前的工作目录,它会随着程序执行的不同而变化。
总结
| 平台 | 获取方法 |
|---|---|
| Linux/Unix | 使用 readlink("/proc/self/exe") 获取路径 |
| Windows | 使用 GetModuleFileName 获取路径 |
| macOS/Linux | 使用 realpath("/proc/self/exe") 获取路径 |
| 跨平台 | 使用 C++17 的 std::filesystem::current_path() |
你可以根据所使用的平台选择合适的方法来获取当前程序的执行目录。