使用golang获取linux上文件的访问/创建/修改时间
作者:apocelipes 时间:2024-04-25 15:24:14
在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上文件的访问/创建/修改时间网站的支持!
来源:https://www.cnblogs.com/apocelipes/archive/2018/08/01/9401923.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
在Python运行时动态查看进程内部信息的方法
对Python3 pyc 文件的使用详解
ASP利用TCPIP.DNS组件实现域名IP查询
Python面向对象编程之类的概念
python实现Dijkstra静态寻路算法
![](https://img.aspxhome.com/file/2023/1/97731_0s.jpg)
超详细注释之OpenCV操作图像平移转换
![](https://img.aspxhome.com/file/2023/6/109886_0s.jpg)
这些关于Go中interface{}的注意事项你都了解吗
Python简单实现TCP包发送十六进制数据的方法
Python Numpy实现计算矩阵的均值和标准差详解
![](https://img.aspxhome.com/file/2023/7/92317_0s.png)
MYSQL中Truncate的用法详解
Python爬取股票交易数据并可视化展示
![](https://img.aspxhome.com/file/2023/8/133718_0s.jpg)
解析Anaconda创建python虚拟环境的问题
![](https://img.aspxhome.com/file/2023/6/61196_0s.png)
对python抓取需要登录网站数据的方法详解
Django实现静态文件缓存到云服务的操作方法
sqlserver数据库移动数据库路径的脚本示例
keras的get_value运行越来越慢的解决方案
![](https://img.aspxhome.com/file/2023/5/124365_0s.png)
Go语言中的流程控制结构和函数详解
![](https://img.aspxhome.com/file/2023/3/103053_0s.png)
Oracle 8x监控sysdba角色用户登陆情况
Python中使用copy模块实现列表(list)拷贝
用来将对象持久化的python pickle模块
![](https://img.aspxhome.com/file/2023/4/134984_0s.png)