10

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.

Elle Fie
  • 681
  • 6
  • 21

1 Answers1

10

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
peterSO
  • 158,998
  • 31
  • 281
  • 276
  • 3
    this the right answer. As an addition being platform specific is advisable to communicate that by giving the suffix `_unix.go` to the module i.e. `mymodule_unix.go` – fabrizioM Nov 11 '14 at 00:14
  • 1
    @fabrizioM: That's too simplistic. See [package build](http://golang.org/pkg/go/build/). – peterSO Nov 11 '14 at 00:45