【问题标题】:get_cwd() from linked directoryget_cwd() 从链接目录
【发布时间】:2016-04-04 14:32:29
【问题描述】:

我有一个程序可以打印我从中获取的当前目​​录

How to get the current directory in a C program?

效果很好。

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

例如,我需要

/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 技能,也许我缺少一些东西?

【问题讨论】:

  • 使用绝对目录?
  • 您想获取符号链接指向的路径吗?您可以使用 readlink(2) 来做到这一点。
  • @AndySchweig:很明显,op 不想获取符号链接指向的路径。
  • 抱歉,误读了问题。

标签: c unistd.h


【解决方案1】:

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

【讨论】:

  • 这个基本正确。在 POSIX 中查找 cd-P-L 选项指定物理和逻辑目录名称。 -P 选项的作用类似于realpath()getcwd(),计算从根目录到给定/当前目录的直接路径。 -L 选项需要 shell 支持; shell 必须记住它是如何到达当前目录的,并且它使用保存的信息返回它的来源。
【解决方案2】:

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

#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;
}

【讨论】:

  • 这是可颠覆的:PWD=/epsilon/delta/gamma/beta/alpha env | grep PWD 表明PWD 可以设置为任意值。
  • 即使没有直接颠覆也不是完全可靠的。它检测路径的最后一个元素是否是符号链接,但中间元素可能是符号链接。给定一个真实目录/home/person/subdir1,包含另一个真实目录/home/person/subdir1/leafdir 和一个引用subdir1 的符号链接/home/person/subdir2,并且用户执行cd /home/person/subdir2/leafdir,那么即使是符号链接,您的代码也会报告“不是链接”被遍历到leafdir
  • @JonathanLeffler :感谢您指出PWD 是可颠覆的。但我想检查是否遍历了符号目录以到达当前目录不是 op 任务的一部分。.
  • 第二个是极端情况,不是主要问题。你可以从中得到一些稍微有趣的结果。符号链接需要跳过更多目录才能真正有趣,但是解释设置更加复杂,并且所需的结果并不完全清楚。在 Mac 上,执行(cd subdir2/leafdir; /bin/pwd) 会通过subdir2 打印路径;执行(cd subdir2/leafdir; unset PWD; /bin/pwd) 会通过subdir1 打印路径——就像使用realpath() 系统调用一样。
猜你喜欢
  • 1970-01-01
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
  • 1970-01-01
  • 2021-05-07
  • 2012-04-19
相关资源
最近更新 更多