Directory size. What 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.
Example. The Go program introduces a GetDirectorySize function that receives a path string (a folder path) and returns an int64 value indicating the total size.
Step 1 In the main() function we call GetDirectorySize with different arguments—be sure to change the arguments to an existing path.
Step 2 We call os.Open to open the directory. We handle errors by testing the error return value against nil.
Step 3 We enumerate all the files in the directory by using a for-range loop over the result value of Readdir.
Step 4 We close the directory (this can help in more complex programs that perform many concurrent tasks) and return the total size as a 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
Results. 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.
Warning The method will not handle nested directories correctly. Additional logic would be needed to support this.
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.