Linux中获取当前程序路径的方法

本文介绍了通过不同的编程方式获取当前工作目录的方法,包括使用shell脚本、C语言的两种不同实现方式,以及利用getcwd函数实现的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、命令行实现:转自:http://www.linuxdiyf.com/viewarticle.php?id=84177

#!/bin/sh

cur_dir=$(pwd)

echo $cur_dir

注意:在cur_dir后没空格,=后面也不能有空格,不然它会认为空格不是路径而报错

2、程序实现:转自:http://topic.youkuaiyun.com/u/20071217/13/78e81ffa-b30c-4685-a58a-2eb5e181b825.html

#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

int getpath(char *buf)
{
long size;
char *ptr;
size = pathconf(".",_PC_PATH_MAX);
if((ptr = (char*)malloc((size_t)size)) != NULL)
{
memset(ptr,0,size);
sprintf(ptr,"/proc/%d/exe",getpid());
}

else

return -1;


return readlink(ptr,buf,size);
}


int main()
{
char buf[128];
getpath(buf);
printf("%s\n",buf);
}

转自:http://hi.baidu.com/jrckkyy/blog/item/6f74ebee3b4768e3b3fb9542.html

http://hi.baidu.com/xlt1888/blog/item/0958fd86668b73cc9123d99f.html

#include <unistd.h>
#include <stdio.h>

int main(int argc , char* argv[])
{
char buf[1024] = { 0 };
int n=0;

n =readlink("/proc/self/exe" , buf , sizeof(buf));
if( n > 0 && n < (int)sizeof(buf))
{

Buf[n]= ‘\0’;
printf("%s\n", buf);
}
}

还可以利用getcwd函数来实现。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值