计算Go中文件的硬链接

时间:2014-11-10 23:31:21

标签: unix go stat hardlink

根据man page for 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)
}

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

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

1 个答案:

答案 0 :(得分: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)
}

输出:

1