Directory
sizeWhat is the total size of all files within a directory? With the Go language we can access the metadata from the filesystem, and then sum up the total bytes.
By calling Readdir
, we can get the size from each FileInfo
struct
returned. We cannot use ReadDir
(uppercase Dir) in the same way, as it does not allow the Size
to be accessed.
The Go program introduces a GetDirectorySize
function that receives a path string
(a folder path) and returns an int64
value indicating the total size.
main()
function we call GetDirectorySize
with different arguments—be sure to change the arguments to an existing path.os.Open
to open the directory. We handle errors by testing the error return value against nil
.for-range
loop over the result value of Readdir
.int64
.package main import ( "fmt" "os" ) func GetDirectorySize(folder string) int64 { // Step 2: read directory and handle errors. dirRead, err := os.Open(folder) if err != nil { panic(err) } dirFiles, err := dirRead.Readdir(0) if err != nil { panic(err) } // Step 3: sum up Size of all files in the directory. sum := int64(0) for _, fileHere := range dirFiles { sum += fileHere.Size() } // Step 4: close directory and return the sum. dirRead.Close() return sum } func main() { // Step 1: call GetDirectorySize and print size of some directories. sum1 := GetDirectorySize("programs/") sum2 := GetDirectorySize("site/") fmt.Println(sum1) fmt.Println(sum2) }10514648 277682
In the screenshot, we can see that the "programs" directory size was reported by macOS to be the same value as that printed by the Go program.
With the "os" package we can open a directory, loop over the files in it, and sum up their sizes. The files themselves do not need to be opened, which can improve performance.