在linux下,获取应用程序工作目录及程序名的方式:
1、main方法中,argv[0]是程序名
int main(int argc, char **argv)
{
char *app = argv[0];
printf("app:%s\n", app);
return 0;
}
2、通过函数getcwd()、getenv("PWD")来获取工作目录
int main(int argc, char **argv)
{
char *path;
path = getcwd(); // or path = getenv("PWD");
printf("currenr path:%s\n", path);
return 0;
}
3、通过函数readlink("/proc/self/exe", buf, buf_size)或readlink("/proc/pid/exe", buf, buf_size)来获取应用程序的绝对路径(含程序名)
int main(int argc, char **argv)
{
char buf[1024];
int count = readlink("proc/self/exe", buf, 1024);
if(count < 0 || count >= 1024){
printf("readlink error:%s\n", strerror(errno));
return 0;
}
buf[count] = '\0';
char *app = strrchr(buf, '/');
*app++ = '\0';
printf("current path:%s\n", buf);
printf("app name:%s\n", app);
return 0;
}
int main(int argc, char **argv)
{
pid_t pid = getpid();
char buf[1024];
char exe[255];
snprintf(exe, 255, "/proc/%d/exe", pid);
int count = readlink("proc/self/exe", buf, 1024);
if(count < 0 || count >= 1024){
printf("readlink error:%s\n", strerror(errno));
return 0;
}
buf[count] = '\0';
char *app = strrchr(buf, '/');
*app++ = '\0';
printf("current path:%s\n", buf);
printf("app name:%s\n", app);
return 0;
}
阅读(1361) | 评论(0) | 转发(0) |