Get file inode in Go

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

Get file inode in Go

问题

如何在Go中获取文件的inode?

我已经可以像这样打印它:

file := "/tmp/system.log"
fileinfo, _ := os.Stat(file)
fmt.Println(fileinfo.Sys())
fmt.Println(fileinfo)

查看Go的实现,很明显要找一些stat方法,但我仍然没有找到Unix系统的结构定义。

如何直接获取inode值?

源代码中哪个文件定义了Sys()的结构?

英文:

How can I get a file inode in Go?

I already can print it like this:

file := "/tmp/system.log"
fileinfo, _ := os.Stat(file)
fmt.Println(fileinfo.Sys())
fmt.Println(fileinfo)

Looking at Go implementation it was obvious looking for some stat method, but I still did not manage to find the structure definition for a Unix system.

How can I get the inode value directly?

Which file/s in the source code define the structure of Sys()?

答案1

得分: 22

你可以使用类型断言来从fileinfo中获取底层的syscall.Stat_t,代码如下:

package main

import (
	"fmt"
	"os"
	"syscall"
)

func main() {
	file := "/etc/passwd"
	fileinfo, _ := os.Stat(file)
	fmt.Printf("fileinfo.Sys() = %#v\n", fileinfo.Sys())
	fmt.Printf("fileinfo = %#v\n", fileinfo)
	stat, ok := fileinfo.Sys().(*syscall.Stat_t)
	if !ok {
		fmt.Printf("Not a syscall.Stat_t")
		return
	}
	fmt.Printf("stat = %#v\n", stat)
	fmt.Printf("stat.Ino = %#v\n", stat.Ino)
}

希望对你有帮助!

英文:

You can use a type assertion to get the underlying syscall.Stat_t from the fileinfo like this

package main

import (
	"fmt"
	"os"
	"syscall"
)

func main() {
	file := "/etc/passwd"
	fileinfo, _ := os.Stat(file)
	fmt.Printf("fileinfo.Sys() = %#v\n", fileinfo.Sys())
	fmt.Printf("fileinfo = %#v\n", fileinfo)
	stat, ok := fileinfo.Sys().(*syscall.Stat_t)
	if !ok {
		fmt.Printf("Not a syscall.Stat_t")
		return
	}
	fmt.Printf("stat = %#v\n", stat)
	fmt.Printf("stat.Ino = %#v\n", stat.Ino)
}

答案2

得分: 11

你可以执行以下操作:

file := "/tmp/system.log"
var stat syscall.Stat_t
if err := syscall.Stat(file, &stat); err != nil {
    panic(err)
}
fmt.Println(stat.Ino)

其中 stat.Ino 是你要查找的 inode。

英文:

You can do the following:

file := "/tmp/system.log"
var stat syscall.Stat_t
if err := syscall.Stat(file, &stat); err != nil {
	panic(err)
}
fmt.Println(stat.Ino)

Where stat.Ino is the inode you are looking for.

答案3

得分: -1

包syscall现已弃用。请参阅https://pkg.go.dev/golang.org/x/sys。

英文:

Package syscall is now deprecated. See https://pkg.go.dev/golang.org/x/sys instead.

huangapple
  • 本文由 发表于 2015年2月5日 16:22:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/28339240.html
匿名

发表评论

匿名网友

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

确定