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

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

Counting hard links to a file in Go

问题

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

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

在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:

  1. type FileInfo interface {
  2. Name() string // base name of the file
  3. Size() int64 // length in bytes for regular files; system-dependent for others
  4. Mode() FileMode // file mode bits
  5. ModTime() time.Time // modification time
  6. IsDir() bool // abbreviation for Mode().IsDir()
  7. Sys() interface{} // underlying data source (can return nil)
  8. }

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上,

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "syscall"
  6. )
  7. func main() {
  8. fi, err := os.Stat("filename")
  9. if err != nil {
  10. fmt.Println(err)
  11. return
  12. }
  13. nlink := uint64(0)
  14. if sys := fi.Sys(); sys != nil {
  15. if stat, ok := sys.(*syscall.Stat_t); ok {
  16. nlink = uint64(stat.Nlink)
  17. }
  18. }
  19. fmt.Println(nlink)
  20. }

输出:

  1. 1
英文:

For example, on Linux,

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;os&quot;
  5. &quot;syscall&quot;
  6. )
  7. func main() {
  8. fi, err := os.Stat(&quot;filename&quot;)
  9. if err != nil {
  10. fmt.Println(err)
  11. return
  12. }
  13. nlink := uint64(0)
  14. if sys := fi.Sys(); sys != nil {
  15. if stat, ok := sys.(*syscall.Stat_t); ok {
  16. nlink = uint64(stat.Nlink)
  17. }
  18. }
  19. fmt.Println(nlink)
  20. }

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:

确定