答案:C++中获取可执行文件路径的方法因操作系统而异,Linux下可通过读取/proc/self/exe获取完整路径,Windows使用GetModuleFileName函数,跨平台项目可结合预处理宏统一封装,再利用std::filesystem提取目录;需注意工作目录与可执行文件路径的区别、缓冲区大小、权限问题及容错处理。

在C++中获取可执行文件的当前路径,也就是程序运行时所在的路径,有多种方法,具体取决于操作系统。下面介绍几种常见且实用的方式。
/proc/self/exe这个符号链接来获取可执行文件的完整路径。示例代码:
#include <iostream>
#include <limits.h>
#include <unistd.h>
<p>std::string getExecutablePath() {
char result[PATH_MAX];
ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
if (count != -1) {
return std::string(result, count);
}
return "";
}
#include <string>
#include <filesystem>
<p>std::string getExecutableDir() {
std::string path = getExecutablePath();
return std::string(std::filesystem::path(path).parent_path());
}
GetModuleFileName函数获取可执行文件的完整路径。示例代码:
#include <iostream>
#include <windows.h>
#include <string>
<p>std::string getExecutablePath() {
char buffer[MAX_PATH];
GetModuleFileNameA(NULL, buffer, MAX_PATH);
return std::string(buffer);
}
std::filesystem提取目录:std::string getExecutableDir() {
std::string path = getExecutablePath();
return std::string(std::filesystem::path(path).parent_path());
}
#include <string>
#include <filesystem>
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#include <limits.h>
#endif
<p>std::string getExecutableDir() {
char buffer[PATH_MAX];
std::string execPath;</p><h1>ifdef _WIN32</h1><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">GetModuleFileNameA(nullptr, buffer, MAX_PATH);
execPath = std::string(buffer);ssize_t len = readlink("/proc/self/exe", buffer, sizeof(buffer)-1);
if (len != -1) {
buffer[len] = '\0';
execPath = std::string(buffer);
}return std::string(std::filesystem::path(execPath).parent_path());
}
<filesystem>处理路径操作,更安全、简洁。/proc可能不可访问,需做容错处理。基本上就这些。根据你的目标平台选择合适的方法,跨平台项目建议封装成统一接口。
以上就是c++++怎么获取可执行文件的当前路径_c++获取程序运行路径的方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号