【问题标题】:Having a dirent that is a symbolic link, how can I get the link-target's path name?有一个符号链接的dirent,我怎样才能得到链接目标的路径名?
【发布时间】:2019-04-06 18:40:05
【问题描述】:

使用opendir() 打开一个目录并使用readdir() 读出它的条目后,我检查该条目是否是符号链接,如果是,我想使用目标的名称。

(假设我们有一个目录exampledir,其中有一个名为linkfile 的符号链接文件链接到目录/path/to/link/target

这是一个简化的 sn-p:

#include <sys/types.h> 
#include <dirent.h>
// ...
const char *path_to_dir = "./exampledir"; 
DIR *dir = opendir(path_to_dir); 
dirent *entry = readdir(dir); 
if (entry->d_type == DT_LNK) {
  // find out the link target's name and store / use it, 
  // but how...? 
}

【问题讨论】:

  • 请注意direntd_type 字段是非标准的,并且并非在所有系统上都存在。
  • 还要注意opendirreaddir 可以在出现错误时返回NULL。

标签: c symlink readdir opendir


【解决方案1】:

使用readlink/readlinkat(2) 系统调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-18
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多