Go文件信息读取
Go文件信息读取
Alex使用go读取文件信息,获取文件名、尺寸、权限等信息。
- 使用os.Stat()可以获取文件信息
| 1 | f, e := os.Stat(file) | 
- 能够读取到的参数1 
 2
 3
 4
 5
 6
 7
 8type 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)
 }通过file.sys()可以获取到更详细内容信息 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18//能够获取到的字段 
 type Stat_t struct {
 Dev uint64
 Ino uint64
 Nlink uint64
 Mode uint32
 Uid uint32
 Gid uint32
 X__pad0 int32
 Rdev uint64
 Size int64
 Blksize int64
 Blocks int64
 Atim Timespec
 Mtim Timespec
 Ctim Timespec
 X__unused [3]int64
 }完整实例代码 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27package main 
 import (
 "os"
 "fmt"
 "reflect"
 )
 func main() {
 file := "./info.go"
 f, e := os.Stat(file)
 fmt.Println(f,e)
 fmt.Println(f.Name()) //文件名
 fmt.Println(f.IsDir()) //是否目录
 fmt.Println(f.Mode()) //文件权限
 fmt.Println(f.ModTime()) //修改时间
 fmt.Println(f.Size()) //文件大小 默认单位b
 fmt.Println(f.Sys())
 if fileInfo, err := os.Stat(file); err == nil {
 Atim := reflect.ValueOf(fileInfo.Sys())
 fmt.Println(Atim)
 fmt.Println(Atim.Elem().FieldByName("Size"))
 }
 }输出 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10&{info.go 520 420 {63629718606 0 0x183260} {16777220 33188 1 19905738 503 80 0 [0 0 0 0] {1494121806 0} {1494121806 0} {1494121806 0} {1494121806 0} 520 8 4096 0 0 0 [0 0]}} <nil> 
 info.go
 false
 -rw-r--r--
 2017-05-07 09:50:06 +0800 CST
 520
 &{16777220 33188 1 19905738 503 80 0 [0 0 0 0] {1494121806 0} {1494121806 0} {1494121806 0} {1494121806 0} 520 8 4096 0 0 0 [0 0]}
 &{16777220 33188 1 19905738 503 80 0 [0 0 0 0] {1494121806 0} {1494121806 0} {1494121806 0} {1494121806 0} 520 8 4096 0 0 0 [0 0]}
 520
