1

我有一个程序来打印我从中获得的当前目录

如何在 C 程序中获取当前目录?

效果很好。

但是,如何为链接目录执行此操作?

例如,我需要

/home/user/Directory

而不是链接目录

/mnt/data/user/Directory

那是,

lrwxrwxrwx  1 user  user 23 Apr  2  2015 Directory -> /mnt/data/user/Directory//

drwxrwxrwx 1 user  user 23 Apr  2  2015 Directory

我正在尝试扩展我的 C 技能,也许我缺少一些东西?

4

2 回答 2

2

我想我现在了解情况了。如我错了请纠正我。你已经通过 cd'ing 到了这个目录/home/user/Directory。到达那里后,您运行程序并getcwd返回/mnt/data/user/Directory,但您想要的是/home/user/Directory. 是这样吗?如果是这样,系统不知道您是通过符号链接进入该目录的,因此它无法为您提供/home/user/Directory. 但是,大多数 shell 将PWD环境变量设置为当前目录,这取决于您 cd'ing 到的内容,因此PWD很可能/home/user/Directory在 cd'ing 到该目录之后包含。我不确定这对您的情况是否有帮助。

于 2016-04-05T02:16:53.340 回答
0

这是一个演示,但没有太多错误检查:

#include<stdio.h>
#include<unistd.h>
#include<sys/stat.h> /* For retrieving file stats */
#include<sys/types.h>
#include<stdlib.h>


int main()
{

struct stat info;
char *target;
char *const ptr=getenv("PWD");

printf("Current working directory : %s\n",ptr);

/* Now, checking to see if your current directory is a link */

if(lstat(ptr,&info)==0)
{
  if(S_ISLNK(info.st_mode))
  {
    target=(char*)malloc((info.st_size+1)*sizeof(char));
    readlink(ptr,target,info.st_size+1);
    target[info.st_size]='\0';
    printf("Current directory is a link\n");
    printf("Target directory : %s\n",target);
    free(target);
  }
  else
  {
    printf("Current directory is not a link\n");
  }
}
else
{
   printf("Sorry! Cannot stat the file\n");
   exit(-1);
}

return 0;
}
于 2016-04-05T03:56:24.570 回答