basic coder » linux下获取当前程序的绝对路径

basic coder » linux下获取当前程序的绝对路径

linux下获取当前程序的绝对路径

2010年2月25日
levin 发表评论
阅读评论
5,072 人阅读过  

在linux下运行的程序经常需要获取自己的绝对路径,程序可能需要引用外部的资源文件,比如在../skin/目录下的图片,这样普通程序是没有问题,但当程序在安装到/usr/bin/目录中,或者为程序建立连接以后就会出现问题,我们可以直接通过运行程序的链接来运行程序,这样../skin/目录就找不到了,因为当前目录并不是程序所在的目录,而且链接所在的目录,所以在它的上一级目录中根本找不到skin目录,所以就需要获取程序的绝对路径,用到了一个函数readlink,原型如下:

1
2
3
#include <unistd.h>
 
ssize_t readlink(const char *restrict path , char *restrict buf , size_t bufsize);

该函数的作用是读取符号链接的原路径,将它存到buf中,返回添充到buf中的字节数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <unistd.h>
#include <stdio.h>
 
int main(int argc , char* argv[])
{
	char buf[1024] = { 0 };
	int n;
 
	n = readlink("/bin/mail" , buf , sizeof(buf));
	if( n > 0 && n < sizeof(buf))
	{
		printf("%s\n" , buf);
	}
}

程序运行后输出:/usr/bin/mailx

linux系统中有个符号链接:/proc/self/exe 它代表当前程序,所以可以用readlink读取它的源路径就可以获取当前程序的绝对路径,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <unistd.h>
#include <stdio.h>
 
int main(int argc , char* argv[])
{
	char buf[1024] = { 0 };
	int n;
 
	n = readlink("/proc/self/exe" , buf , sizeof(buf));
	if( n > 0 && n < sizeof(buf))
	{
		printf("%s\n" , buf);
	}
}
1
2
ouclwp@darkstar:~/socket$ ./read
/home/ouclwp/socket/read
原文地址:https://www.cnblogs.com/lexus/p/2599456.html