获取程序当前执行绝对路径
源码
#include <unistd.h>
#include <stdio.h>
#include <string.h>
static char* get_app_path()
{
const int MAX_PATHSIZE = 256;
static char cur_app_path[MAX_PATHSIZE] = {0};
if(cur_app_path[0]) return cur_app_path;
ssize_t length = ::readlink("/proc/self/exe",cur_app_path,MAX_PATHSIZE-1);
int path_len = strlen(cur_app_path);
for(int i = path_len; i>=0; --i)
{
if(cur_app_path[i] == '/' || cur_app_path[i] == '\\')
{
cur_app_path[i+1] = '\0';
break;
}
}
printf("cur_app_path=%s\n",cur_app_path);
return cur_app_path;
}
int main()
{
get_app_path();
return 0;
}
运行
[banting@localhost test]$ g++ -g app_path.cpp -o app_path
[banting@localhost test]$ ./app_path
cur_app_path=/home/banting/test/
[banting@localhost test]$ pwd
/home/banting/test
[banting@localhost test]$