Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file inode in Go

Tags:

unix

go

inode

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()?

like image 636
SystematicFrank Avatar asked Feb 05 '15 08:02

SystematicFrank


People also ask

How do you display inode?

Handy inode commands on Linux Use -inum to find files associated with a certain inode. Inversely, use ls-i to get the inode number of a file. ls -i Command: display inode$ls -i /dir/bluem_article129792 /dir/bluem_article129792 is the inode of /dir/bluem_article.

Where is inode stored?

The inode table is stored in the logic disk block. Each entry of inode table stores some file attributes, such as file size, permission, ownership, disk block address, time of last modification etc.

What information is stored in inode?

By definition, an inode is an index node. It serves as a unique identifier for a specific piece of metadata on a given filesystem. Each piece of metadata describes what we think of as a file. That's right, inodes operate on each filesystem, independent of the others.


2 Answers

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)
}
like image 128
Nick Craig-Wood Avatar answered Oct 16 '22 19:10

Nick Craig-Wood


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.

like image 25
serejja Avatar answered Oct 16 '22 21:10

serejja