1. 函数原型
func Stat(name string) (FileInfo, error)
2. FileInfo数据结构
// A FileInfo describes a file and is returned by Stat and Lstat.
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)
}
3. 应用举例
package main
import (
"fmt"
"os"
)
func main() {
list := os.Args
if len(list) != 2 {
fmt.Println("Usage: .\\main.exe file")
return
}
fileName := list[1]
info, err := os.Stat(fileName)
if err != nil {
fmt.Println("get fileInfo failed:", err)
return
}
fmt.Println("name = ", info.Name())
fmt.Println("size = ", info.Size())
}
/*
output:
PS E:\Code\GoCode\GetFileAttr> go run .\main.go .\go.mod
name = go.mod
size = 28
PS E:\Code\GoCode\GetFileAttr> go build .\main.go
PS E:\Code\GoCode\GetFileAttr> .\main.exe main.go
name = main.go
size = 369
*/
本文详细介绍了Golang中获取文件信息的Stat函数,包括其函数原型、FileInfo数据结构的解析,并通过具体应用案例进行说明。

被折叠的 条评论
为什么被折叠?



