c++ 获取当前执行文件的绝对路径
at 1年前 ca Cpp & C pv 1891 by touch
要在运行时获取当前执行文件的绝对路径,可以使用不同平台特定的API来实现。以下是Windows和Linux平台的具体实现方法。
Windows 平台
在Windows上,可以使用 GetModuleFileName 函数获取当前模块的文件名(包括路径)。
#include <windows.h>
#include <iostream>
#include <string>
std::string getExecutablePath() {
char path[MAX_PATH];
GetModuleFileNameA(NULL, path, MAX_PATH);
return std::string(path);
}
int main() {
std::string executablePath = getExecutablePath();
std::cout << "Current executable path: " << executablePath << std::endl;
return 0;
}Linux 平台
在Linux上,可以读取 /proc/self/exe 符号链接来获取当前可执行文件的路径。
#include <unistd.h>
#include <limits.h>
#include <iostream>
#include <string>
std::string getExecutablePath() {
char path[PATH_MAX];
ssize_t count = readlink("/proc/self/exe", path, PATH_MAX);
if (count != -1) {
path[count] = '\0';
return std::string(path);
} else {
throw std::runtime_error("Error getting executable path");
}
}
int main() {
try {
std::string executablePath = getExecutablePath();
std::cout << "Current executable path: " << executablePath << std::endl;
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
}
return 0;
}跨平台实现
为了使代码能够在不同平台上运行,可以使用条件编译来选择适当的实现:
#include <iostream>
#include <string>
#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
std::string getExecutablePath() {
char path[MAX_PATH];
GetModuleFileNameA(NULL, path, MAX_PATH);
return std::string(path);
}
#elif defined(__linux__)
#include <unistd.h>
#include <limits.h>
std::string getExecutablePath() {
char path[PATH_MAX];
ssize_t count = readlink("/proc/self/exe", path, PATH_MAX);
if (count != -1) {
path[count] = '\0';
return std::string(path);
} else {
throw std::runtime_error("Error getting executable path");
}
}
#else
#error "Unsupported platform"
#endif
int main() {
try {
std::string executablePath = getExecutablePath();
std::cout << "Current executable path: " << executablePath << std::endl;
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
}
return 0;
}以上代码根据当前平台调用相应的函数来获取可执行文件的路径。确保在编译时定义了正确的宏(如 _WIN32 或 __linux__)以选择合适的平台特定代码。这样,你就可以在不同平台上获取当前执行文件的绝对路径。
版权声明
本文仅代表作者观点,不代表码农殇立场。
本文系作者授权码农殇发表,未经许可,不得转载。