Counting hard links to a file in Go

我只是一个虾纸丫 提交于 2019-12-19 03:37:03

问题


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:


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


来源:https://stackoverflow.com/questions/26854961/counting-hard-links-to-a-file-in-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!