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
Tutorials
+20.2k SSL : How to check if current certificate is sha1 or sha2
+13.3k Golang : Parsing or breaking down URL
+8.1k Golang : Generate Codabar
+9.4k Golang : Simple File Server
+5.1k PHP : How to check if an array is empty ?
+12.6k Golang : How to determine if a year is leap year?
+16.1k Golang : How to make a file read only and set it to writable again?
+5.6k Golang : Humanize and Titleize functions
+6.8k Golang : Get today's weekday name and calculate target day distance example
+9.3k Golang : Generate random integer or float number
+9.7k Golang : Simple image viewer with Go-GTK