Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting hard links to a file in Go

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.

like image 903
Elle Fie Avatar asked Nov 10 '14 23:11

Elle Fie


1 Answers

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
like image 113
peterSO Avatar answered Nov 01 '22 09:11

peterSO