如何在 Go 中获得文件长度?

我查了 Golang.org/pkg/os/#file,但还是不知道。 似乎没有办法得到文件长度,我错过了什么吗?

如何在 Go 中获得文件长度?

86147 次浏览

(*os.File).Stat() returns a os.FileInfo value, which in turn has a Size() method. So, given a file f, the code would be akin to

fi, err := f.Stat()
if err != nil {
// Could not obtain stat, handle error
}


fmt.Printf("The file is %d bytes long", fi.Size())

Slightly more verbose answer:

file, err := os.Open( filepath )
if err != nil {
log.Fatal(err)
}
fi, err := file.Stat()
if err != nil {
log.Fatal(err)
}
fmt.Println( fi.Size() )

If you don't want to open the file, you can directly call os.Stat instead.

fi, err := os.Stat("/path/to/file")
if err != nil {
return err
}
// get the size
size := fi.Size()

Calling os.Stat as sayed by @shebaw (at least in UNIX OS) is more efficient, cause stat() is a Unix system call that returns file attributes about an inode, and is not necessary to deal with open the file.

NOTE: Using other method can lead to too many open files in multithread/concurrency application, due to the fact that you open the file for query the stats

Here the benchmark

func GetFileSize1(filepath string) (int64, error) {
fi, err := os.Stat(filepath)
if err != nil {
return 0, err
}
// get the size
return fi.Size(), nil
}


func GetFileSize2(filepath string) (int64, error) {
f, err := os.Open(filepath)
if err != nil {
return 0, err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return 0, err
}
return fi.Size(), nil
}
BenchmarkGetFileSize1-8           704618              1662 ns/op
BenchmarkGetFileSize2-8           199461              5668 ns/op