c++如何获取可执行文件的当前路径_c++获取程序运行路径的方法
发布时间:2025-10-28 23:22
发布者:网络
浏览次数:Windows使用GetModuleFileName获取路径,Linux通过readlink读取/proc/self/exe,跨平台可封装统一函数,注意区分可执行文件路径与当前工作目录。

C++获取可执行文件当前路径的方法在不同操作系统下略有差异,下面介绍几种常见且实用的方式,适用于Windows和Linux平台。
1. Windows平台:使用GetModuleFileName
在Windows系统中,可以通过Windows API GetModuleFileName 获取当前可执行文件的完整路径,然后提取目录部分。示例代码:
#include windows.h>#include
#include iostream>
std::string GetExecutablePath() {
char buffer[MAX_PATH];
GetModuleFileNameA(NULL, buffer, MAX_PATH);
std::string fullPath(buffer);
// 去掉文件名,保留路径
size_t lastSlash = fullPath.find_last_of("\/");
if (lastSlash != std::string::npos) {
return fullPath.substr(0, lastSlash);
}
return ""; // 异常情况
}
调用 GetExecutablePath() 即可获得程序所在目录。
Pinokio
Pinokio是一款开源的AI浏览器,可以安装运行各种AI模型和应用
232
查看详情
2. Linux平台:读取/proc/self/exe符号链接
Linux系统中,每个进程的信息保存在/proc/[pid]/exe,其中/proc/self/exe指向当前程序的可执行文件路径。可以使用readlink函数读取该符号链接。
示例代码:
#include#include
#include
#include
std::string GetExecutablePath() {
char result[PATH_MAX];
ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
if (count != -1) {
std::string fullPath(result, count);
size_t lastSlash = fullPath.find_last_of("/");
if (lastSlash != std::string::npos) {
return fullPath.substr(0, lastSlash);
}
}
return ""; // 失败
}
3. 跨平台封装建议
为了兼容多个平台,可以用宏判断操作系统,统一接口。 #ifdef _WIN32#include windows.h>
#else
#include
#include
#endif
std::string GetCurrentExecutableDirectory() {
#ifdef _WIN32
char buffer[MAX_PATH];
GetModuleFileNameA(NULL, buffer, MAX_PATH);
std::string path(buffer);
#else
char result[PATH_MAX];
ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
std::string path(count == -1 ? "" : std::string(result, count));
#endif
size_t pos = path.find_las
t_of("/\");if (pos != std::string::npos) {
return path.substr(0, pos);
}
return ".";
}
4. 注意事项
获取的路径是程序启动时的可执行文件位置,不是当前工作目录(current working directory)。当前工作目录可用
getcwd()(Linux)或GetCurrentDirectory()(Windows)获取。路径分隔符在不同系统中不同,处理时建议统一判断
/和。
基本上就这些方法,根据目标平台选择合适实现即可。跨平台项目推荐封装统一函数。
以上就是c++++如何获取可执行文件的当前路径_c++获取程序运行路径的方法的详细内容,更多请关注其它相关文章!
# c++
# 程序路径
# linux
# windows
# 操作系统
# ios
# win
# stream
# windows系统
# linux系统
# 可执行文件
# 数据结构
# 自定义
# 尼克
# 如何选择
# 运算符
# 多个
# 换行符
# 可以用
# 西昌家具网站建设推广
# 市南区网站整站优化
# 盐城网站建设总部地址
# 免费seo服务
# 基隆网站优化
# 闲鱼营销推广自己的产品
# 常用网站建设总结报告
# 梅沙品牌网站建设
# 酒吧推广线下怎么做营销
# 松原seo教程案例




