Search code examples
clinuxhardlink

Find all hard links of a certain file


I have a filename for which I have to get all hard links(that are in the same dir).

I thought about using readlink in combination with dir->d_name maneuver, but that only applys to softlinks.

Any ideas?


Solution

  • Go through each file in the directory and lstat() it. If its inode number (st_ino) is the same as the one of the file you're interested in, and they both have the same link count (st_nlink) which is greater than 1, then they're hard-linked together.

    (The link count check isn't strictly necessary, but it's a good sanity check.)