在Go语言中计算文件的硬链接数量

huangapple go评论68阅读模式
英文:

Counting hard links to a file in Go

问题

根据FileInfo的man页面,在Go语言中使用stat()函数获取文件的以下信息:

type FileInfo interface {
    Name() string       // 文件的基本名称
    Size() int64        // 对于普通文件,返回文件的字节长度;对于其他类型的文件,返回与系统相关的值
    Mode() FileMode     // 文件的模式位
    ModTime() time.Time // 文件的修改时间
    IsDir() bool        // 是否为目录的缩写,等同于Mode().IsDir()
    Sys() interface{}   // 底层数据源(可能返回nil)
}

在Go语言中如何获取特定文件的硬链接数?

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

英文:

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 (&lt;sys/stat.h&gt;) defines st_nlink ("reference count of hard links") as a return value from a stat() system call.

答案1

得分: 10

例如,在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
英文:

For example, on Linux,

package main

import (
	&quot;fmt&quot;
	&quot;os&quot;
	&quot;syscall&quot;
)

func main() {
	fi, err := os.Stat(&quot;filename&quot;)
	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:

<pre>
1
</pre>

huangapple
  • 本文由 发表于 2014年11月11日 07:31:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/26854961.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定