Linux中获取当前程序路径的方法
1、命令行實(shí)現(xiàn):轉(zhuǎn)自:http://www.linuxdiyf.com/viewarticle.php?id=84177
#!/bin/sh
cur_dir=$(pwd)
echo $cur_dir
注意:在cur_dir后沒(méi)空格,=后面也不能有空格,不然它會(huì)認(rèn)為空格不是路徑而報(bào)錯(cuò)
?
2、程序?qū)崿F(xiàn):轉(zhuǎn)自:http://topic.csdn.net/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);
}
?
轉(zhuǎn)自: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函數(shù)來(lái)實(shí)現(xiàn)。
總結(jié)
以上是生活随笔為你收集整理的Linux中获取当前程序路径的方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 在Ubuntu11.10中安装配置Ope
- 下一篇: Linux下遍历文件夹的实现