clinuxsymlinkstathardlink

how to use lstat() to determine if hard link or not


My OS is linux. I program in C. I know I can use the lstat() to recognize the soft link, i.e., use S_ISLNK(st.st_mode). But how can I recognize the link is a hard link? if the link is a hard link, it will be thought of as a regular file. However, I also want to distinguish the regular file from the hard link. Are there any ways to handle this case?


Solution

  • But how can I recognize the link is hard link?

    You can't.

    A "hard link" isn't actually anything special. It's just a directory entry that happens to point to the same data on disk as a directory entry somewhere else. The only way to reliably identify hard links is to map all the paths on your filesystem to inodes, and then see which ones point to the same value.