How do you check whether a file is a hard link in Go? os.FileMode
only has a mode for symlinks, not hard links.
I had an idea that unfortunately doesn't work:
package main
func main() {
filename := os.Args[1]
var hardlink bool
link, _ := os.Readlink(filename)
fi, _ := os.Stat(filename)
mode := string(fi.Mode().String()[0])
if link != "" && mode != "L" {
hardlink = true
}
fmt.Printf("%v is hard link? %v\n", filename, hardlink)
}
This^ doesn't work because os.Readlink
reads only symlinks, not hard links.
I found a somewhat related answer:
Counting hard links to a file in Go
But this answer shows how to find the number of hard links to a file, not whether a file itself is a hard link.
I'm guessing that the syscall package used in that answer or, better yet, the sys package has a way to test whether a file's a hard link. Does anyone know to do this? (I have trouble understanding those packages because they're so low-level.)
EDIT
I should add the reason why I'd like to check this. I'm trying to make a function to create a tar archive of a directory [using filepath.Walk()
]. In this function, when I create the *tar.Header
for a file, I set a value to *tar.Header.Typeflag
.
For example, if fi
is a file's *os.FileInfo
variable and hdr
is the *tar.Header
variable for that file's place in a new tar archive, it looks like this:
if fi.Mode().IsDir() {
hdr.Typeflag = tar.TypeDir
}
In the tar package, the modes for hard links and regular files are distinct, TypeLink
and TypeReg
, but this isn't the case in the os package. So running this won't set the correct Typeflag
:
hdr.Mode = int64(fi.Mode())