1

I need to list all hard links of a given file in "pure" C, so without help of bash commands.

I googled for hours but couldn't find anything useful. My current idea is to get inode number then loop through directory to find files with same inode.

In bash something like

 sudo find / -inum 199053

Any better suggestion?

Thanks

s.bandara
  • 5,636
  • 1
  • 21
  • 36
user2976389
  • 525
  • 1
  • 5
  • 7
  • This seems UNIX-specific, so I added a tag for you. – s.bandara Jan 25 '15 at 02:48
  • 1
    At the very least, you can do a short-circuit optimization by using `stat` to find out the number of hard links *n* and abort the file system traversal after you have found *n* links (or entirely avoid in case of *n* = 1). But apart from this, I don't know of a more efficient solution. – 5gon12eder Jan 25 '15 at 03:03
  • 1
    You'll want to start the `find` from the filesystem's mount point (which may or may not be `/`), and use the `-xdev` option to stay within that filesystem (since hard links can't cross filesystem boundaries). I don't think there's a better way to do it. Why do you need to do it in "pure C"? The `find` command is likely to be at least as efficient as whatever you can write. – Keith Thompson Jan 25 '15 at 04:09

1 Answers1

2

To get the inode number of a single file, invoke the stat function and reference the st_ino value of the returned struct.

int result;
struct stat s;
result = stat("filename.txt", &s);
if ((result == 0) && (s.st_ino == 199053))
{
   // match
}

You could build a solution with the stat function using opendir, readdir, and closedir to recursively scan a directory hierarchy to look for matching inode values.

You could also use scandir to scan an entire directory:

int filter(const struct dirent* entry)
{
    return (entry->d_ino == 199053) ? 1 : 0;
}

int main()
{ 
    struct dirent **namelist = NULL;
    scandir("/home/selbie", &namelist, filter, NULL);
    free(namelist);
    return 0;
}
selbie
  • 100,020
  • 15
  • 103
  • 173