使用golang获取linux上文件的访问/创建/修改时间

在linux上想获取文件的元信息,我们需要使用系统调用lstat或者stat。

在golang的os包里已经把stat封装成了Stat函数,使用它比使用syscall要方便不少。

这是os.Stat的原型:

func Stat(name string) (FileInfo, error)
    Stat returns a FileInfo describing the named file. If there is an error, it
    will be of type *PathError.

返回一个os.FileInfo,这里面包含有文件的元信息:

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)
}
 A FileInfo describes a file and is returned by Stat and Lstat.

重点看到Sys()这个方法,通过它我们可以获得*syscall.Stat_t,也就是stat和lstat使用并填入文件元信息的struct stat *。
os.FileInfo里的信息并不完整,所以我们偶尔需要使用*syscall.Stat_t来获取自己想要的信息,比如文件的创建时间。
因为Stat_t里的时间都是syscall.Timespec类型,所以我们为了输出内容的直观展示,需要一点helper function:

func timespecToTime(ts syscall.Timespec) time.Time {
 return time.Unix(int64(ts.Sec), int64(ts.Nsec))
}

然后接下来就是获取修改/创建时间的代码:

func main() {
 finfo, _ := os.Stat(filename)
 // Sys()返回的是interface{},所以需要类型断言,不同平台需要的类型不一样,linux上为*syscall.Stat_t
 stat_t := finfo.Sys().(*syscall.Stat_t)
 fmt.Println(stat_t)
 // atime,ctime,mtime分别是访问时间,创建时间和修改时间,具体参见man 2 stat
 fmt.Println(timespecToTime(stat_t.Atim))
 fmt.Println(timespecToTime(stat_t.Ctim))
 fmt.Println(timespecToTime(stat_t.Mtim))
}

这是输出效果:

你会发现修改时间居然提前于创建时间!别担心,那是因为atime,ctime, mtime都可以人为修改,一些从网上下载回来的文件也会包含元信息,所以才会出现这种情况,并不是你穿越了:-P

golang为我们的开发提供了极大的便利,希望大家都能了解和接触这门语言。

总结

以上所述是小编给大家介绍的使用golang获取linux上文件的访问/创建/修改时间,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对来客网网站的支持!