How to Get File Length in Go

Created
Modified

Using file.Stat Function

Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY.

See the following example:

package main

import (
  "fmt"
  "os"
)

func main() {
  f, err := os.Open("access.log")
  if err != nil {
    // log.Fatal(err)
  }
  defer f.Close()

  stat, _ := f.Stat()
  fmt.Println(stat.Size())
  // fmt.Println(FormatByteSI(stat.Size()))
}
2626
2.6 kB

Using os.Stat Function

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

For example,

package main

import (
  "fmt"
  "os"
)

func main() {

  stat, err := os.Stat("access.log")
  if err != nil {
    // log.Fatal(err)
  }
  fmt.Println(stat.Size())
  // fmt.Println(FormatByteSI(stat.Size()))
}
2626
2.6 kB

Related Tags

#file# #length#