获取程序当前执行绝对路径

获取程序当前执行绝对路径

源码

#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]$ 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值