[Golang] Calculate Directory Size Excluding Sub-Directories
Calculate total size of files in directory, excluding sub-directories. We use ioutil.ReadDir to read information of files in directory, and calculate the sum of size of all files.
import (
"io/ioutil"
"os"
)
func calculateDirSize(dirpath string) (dirsize int64, err error) {
err = os.Chdir(dirpath)
if err != nil {
return
}
files, err := ioutil.ReadDir(".")
if err != nil {
return
}
for _, file := range files {
if file.Mode().IsRegular() {
dirsize += file.Size()
}
}
return
}
Tested on: Ubuntu Linux 17.10, Go 1.10
References:
[1] | ioutil - The Go Programming Language |