I looked up golang.org/pkg/os/#File , but still have no idea. Seems there is no way to get file length, did I miss something?
How to get file length in Go?
I looked up golang.org/pkg/os/#File , but still have no idea. Seems there is no way to get file length, did I miss something?
How to get file length in Go?
(*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())
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()
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() )
fi
io.Reader is not being passed on elsewhere, so closing it may be presumptuous.
Apr 15, 2018 at 18:34
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