Get file size in Go




Our mouths have limited size and we still need to cut up our food into edible chunks before putting into our mouths and eat. The same goes to computer world as well.

From time to time, we need to know what is a file's size before we perform operation with/on the file.

In this tutorial, we will learn how to get file size with Go. Below is the code to find out a file size or length in Go

 package main

 import (
 "fmt"
 "os"
 )

 func main() {
 file, err := os.Open("test.txt")
 if err != nil {
 // handle the error here
 return
 }
 defer file.Close()

 // get the file size
 stat, err := file.Stat()
 if err != nil {
 return
 }

 fmt.Println("File size is " + stat.Size())

 }

updated to include calculation in various bytes measurements

 package main

 import (
 "fmt"
 "os"
 )

 func main() {

  file, err := os.Open("test.txt")
  if err != nil {
 return
  }
  defer file.Close()

  stat, err := file.Stat()
  if err != nil {
 return
  }

  var bytes int64
  bytes = stat.Size()


  var kilobytes int64
  kilobytes = (bytes / 1024)

  var megabytes float64
  megabytes = (float64)(kilobytes / 1024) // cast to type float64

  var gigabytes float64
  gigabytes = (megabytes / 1024)

  var terabytes float64
  terabytes = (gigabytes / 1024)

  var petabytes float64
  petabytes = (terabytes / 1024)

  var exabytes float64
  exabytes = (petabytes / 1024)

  var zettabytes float64
  zettabytes = (exabytes / 1024)

  fmt.Println("File size in bytes ", bytes)
  fmt.Println("File size in kilobytes ", kilobytes)
  fmt.Println("File size in megabytes ", megabytes)
  fmt.Println("File size in gigabytes ", gigabytes)
  fmt.Println("File size in terabytes ", terabytes)
  fmt.Println("File size in petabytes ", petabytes)
  fmt.Println("File size in exabytes ", exabytes)

  fmt.Println("File size in zettabytes ", zettabytes)

 }

Result :

File size in bytes 2206048

File size in kilobytes 2154

File size in megabytes 2

File size in gigabytes 0.001953125

File size in terabytes 1.9073486328125e-06

File size in petabytes 1.862645149230957e-09

File size in exabytes 1.8189894035458565e-12

File size in zettabytes 1.7763568394002505e-15





By Adam Ng

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.


Advertisement