find the size of a directory in go

To find the size of a directory in Go, we can use the filepath.Walk function to walk through all the files and directories within a given directory. While walking through the directory, we can use the os.Stat function to get information like file size, mode and modification time. By adding up the file sizes, we can determine the size of the entire directory.

main.go
package main

import (
    "fmt"
    "os"
    "path/filepath"
)

func main() {
    var size int64
    err := filepath.Walk("/path/to/directory", func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        if !info.IsDir() {
            size += info.Size()
        }
        return nil
    })
    if err != nil {
        fmt.Println(err)
    }
    fmt.Printf("Size of directory is %v bytes", size)
}
459 chars
25 lines

In this example, we create a size variable to hold the total size of the directory. We then use filepath.Walk to walk through all the files in the directory, ignoring directories themselves. The Size method on a os.FileInfo interface returns the size of the file in bytes. We can then add up the sizes of all the files to get the total size of the directory. Finally, we print out the size of the directory in bytes.

gistlibby LogSnag