Counting hard links to a file in Go

1.2k views Asked by At

According to the man page for FileInfo, the following information is available when stat()ing a file in Go:

type FileInfo interface {
        Name() string       // base name of the file
        Size() int64        // length in bytes for regular files; system-dependent for others
        Mode() FileMode     // file mode bits
        ModTime() time.Time // modification time
        IsDir() bool        // abbreviation for Mode().IsDir()
        Sys() interface{}   // underlying data source (can return nil)
}

How can I retrieve the number of hard links to a specific file in Go?

UNIX (<sys/stat.h>) defines st_nlink ("reference count of hard links") as a return value from a stat() system call.

1

There are 1 answers

2
peterSO On BEST ANSWER

For example, on Linux,

package main

import (
    "fmt"
    "os"
    "syscall"
)

func main() {
    fi, err := os.Stat("filename")
    if err != nil {
        fmt.Println(err)
        return
    }
    nlink := uint64(0)
    if sys := fi.Sys(); sys != nil {
        if stat, ok := sys.(*syscall.Stat_t); ok {
            nlink = uint64(stat.Nlink)
        }
    }
    fmt.Println(nlink)
}

Output:

1