115

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?

4 Answers 4

162

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

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

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() )
3
  • 9
    Maybe a defer file.Close() before the Stat()?
    – Timmmm
    Feb 26, 2016 at 10:43
  • 1
    @Timmmm yes - but since this is a code snippet, we can't assume that fi io.Reader is not being passed on elsewhere, so closing it may be presumptuous.
    – colm.anseo
    Apr 15, 2018 at 18:34
  • This is generally the correct way to get the size of a file that you will process soon after checking its size. You never close the file until you're done with it, avoids TOCTOU issues.
    – anonymous
    Mar 3 at 21:07
15

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
1
  • GetFileSize1() should NEVER be used if you need to protect against TOCTOU issues. For anyone that does not understand TOCTOU, please google it, they are security problems created by things changing between a time of check and the time of use.
    – anonymous
    Mar 3 at 21:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.