计算Go中文件的硬链接

Ell*_*Fie 5 unix hardlink go stat

根据FileInfo手册页,stat()在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)
}
Run Code Online (Sandbox Code Playgroud)

如何检索Go中特定文件的硬链接数?

UNIX(<sys/stat.h>)定义st_nlink("硬链接的引用计数")作为stat()系统调用的返回值.

pet*_*rSO 7

例如,在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)
}
Run Code Online (Sandbox Code Playgroud)

输出:

1

  • 这是正确的答案.作为平台特定的补充建议通过给模块提供后缀`_unix.go`来传达,即`mymodule_unix.go` (3认同)