I have to write out all hard links on file in C. I have no idea how to do that. One possibility is also to call bash command but which command to call?
Given: file name 'foo.txt'
Find: all files that are hard links to 'foo.txt'
I have to write out all hard links on file in C. I have no idea how to do that. One possibility is also to call bash command but which command to call?
Given: file name 'foo.txt'
Find: all files that are hard links to 'foo.txt'
Get the inode number of the file (ls -i
will give it), then use find root_path_of_the_partition -inum inode_number
.
Beware to find by inode number on the same partition, as it is possible that two different files have the same inode number, provided that they are on different partitions.
The other answer apparently relies on the ls
command, but this can be done without it. Use lstat
to put file (inode) information into a struct stat
. For example:
#include <sys/stat.h>
// ... inside main ...
struct stat stats;
if (argc == 2)
lstat(argv[1], &stats)
printf("Link count: %d\n", stats->st_nlink);
You should also check to see if lstat
failed (if (lstat(argv[1], &stats) != 0) {...}
) before you proceed. Just giving you a starting point for this.
Adding some more code in case you want to find links pertaining to all files in a directory instead of just one file as an argument.
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);
}