Golang 之获取文件信息

本文详细介绍了Golang中获取文件信息的Stat函数,包括其函数原型、FileInfo数据结构的解析,并通过具体应用案例进行说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值