一、建设一个文件a.txt

mkdir stat && cd stat && touch a.txt && touch stat_test.go

二、应用 os.Stat() 获取 file 文件信息

关上 stat_test.go 输出:

package statimport (    "os"    "testing")func TestStat(t *testing.T) {    fileInfo, err := os.Stat("a.txt")    if err != nil {        t.Error(err)    }    t.Log(fileInfo.Name())    //文件名称    t.Log(fileInfo.Size())    //文件的大小    t.Log(fileInfo.Mode())    //fileMode    t.Log(fileInfo.ModTime()) //批改工夫    t.Log(fileInfo.IsDir())   //是否是目录}

输入:

a.txt0-rw-r--r--2022-08-16 15:23:46.956139863 +0800 CSTfalse

三、os.Stat()源码剖析

在源码src/os/stat.go咱们能够看到

// Stat 返回 一个形容这个文件的  FileInfo 接口 .// If there is an error, it will be of type *PathError.func Stat(name string) (FileInfo, error) {    testlog.Stat(name)    return statNolog(name)}

咱们在看一下 FileInfo 接口

// A FileInfo describes a file and is returned by Stat and Lstat.type FileInfo interface {    Name() string       // 文件名称    Size() int64        // 文件的字节长度    Mode() FileMode     // file mode bits    ModTime() time.Time // 批改工夫    IsDir() bool        // 是否是一个目录    Sys() interface{}   // underlying data source (can return nil)}

咱们在看一下 FileMode 数据结构

// A FileMode 展现一个文件的  mode(模式) and permission(权限) bits.type FileMode uint32