• 如何用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为我们的开发提供了极大的便利,希望大家都能了解和接触这门语言。

  • 相关阅读:
    宏__cplusplus
    linux C 可变参数类型va_list
    muduo笔记 网络库(六)Socket类及SocketsOps库函数封装
    LeetCode74 搜索二维矩阵
    babelpolyfill
    babel预设和插件
    wordwrap和wordbreak的区别
    react高级知识
    使用schematics简化脚手架开发
    js循环删除数组元素的方法
  • 原文地址:https://www.cnblogs.com/apocelipes/p/9401923.html
Copyright © 2020-2023  润新知