-3

我必须在 C 文件中写出所有硬链接。我不知道该怎么做。一种可能性是调用 bash 命令,但调用哪个命令?

给定:文件名'foo.txt'

查找:所有硬链接到 'foo.txt' 的文件

4

2 回答 2

2

获取文件的 inode 号(ls -i会给它),然后使用find root_path_of_the_partition -inum inode_number. 请注意在同一分区上通过 inode 编号查找,因为两个不同的文件可能具有相同的 inode 编号,前提是它们位于不同的分区上。

于 2014-05-30T13:39:04.813 回答
1

另一个答案显然依赖于ls命令,但没有它也可以做到。用于lstat将文件(inode)信息放入struct stat. 例如:

#include <sys/stat.h>
// ... inside main ...
struct stat stats;
if (argc == 2)
  lstat(argv[1], &stats)
printf("Link count: %d\n", stats->st_nlink);

在继续之前,您还应该检查是否lstat失败 ( )。if (lstat(argv[1], &stats) != 0) {...}只是给你一个起点。


添加更多代码,以防您想查找与目录中所有文件有关的链接,而不仅仅是一个文件作为参数。

DIR *dp; 
struct stat stats;
// ...
if ((dp = opendir(".")) == NULL) {
    perror("Failed to open directory");
    exit(-1);
}

while ((dir = readdir(dp)) != NULL) {
    if (lstat(dir->d_name, &stats) != 0) {
        perror("lstat failed: ");
        exit(-1);
    }

    printf("Link count: %d\n, stats->st_nlink);
}
于 2014-05-30T14:51:59.860 回答