工作目录和程序放置的目录是不同的概念,举个例子,比如我的程序 a.out 放置在 /root/a.out
工作目录:比如我当前目录是 /home 然后我运行目录 /root/a.out 那么工作目录就是 /home,如果我在 /home/test 目录下执行命令/root/a.out,那么 工作目录就是 /home/test
程序实际放置目录:我在任何的目录下运行命令 /root/a.out ,我的程序的实际放置目录都是 /root/a.out ,只要我不挪动 a.out 的位置
代码比较简单,没有过多解释,拿到这个路径之后,就可以拼接路径,去上一级目录等
#include
#include
#include
// 工作目录
void getWorkPath()
{
char path[1024];
getcwd(path,1023);
// getcwd的返回值是一个字符串类型,没有错误就返回path,有错误就返回错误
printf("the file work path: %s\n", path);
}
// 程序实际放置目录
void getPath()
{
char path[1024] = {0};
int ret = readlink("/proc/self/exe", path, 1023);
if (ret > 0) {
printf("the file path: %s\n", path);
printf("the file path dir: %s\n", dirname(path));
}
else
printf("error\n");
}
int main()
{
getPath();
getWorkPath();
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)