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() )