Golang : Find file size(disk usage) with filepath.Walk
Need to determine which file is taking up all the disk space? Maybe this small Golang program can be useful to you. The purpose of this small Golang program is to find out how much space a file occupies in a given target directory.
package main
import (
"fmt"
"os"
)
// function to return the disk usage information
func diskUsage(currentPath string, info os.FileInfo) int64 {
size := info.Size()
if !info.IsDir() {
return size
}
dir, err := os.Open(currentPath)
if err != nil {
fmt.Println(err)
return size
}
defer dir.Close()
files, err := dir.Readdir(-1)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for _, file := range files {
if file.Name() == "." || file.Name() == ".." {
continue
}
size += diskUsage(currentPath+"/"+file.Name(), file)
}
fmt.Printf("Size in bytes : [%d] : [%s]\n", size, currentPath)
return size
}
func main() {
if len(os.Args) != 2 {
fmt.Printf("USAGE : %s <target_directory> \n", os.Args[0])
os.Exit(0)
}
dir := os.Args[1] // get the target directory
info, err := os.Lstat(dir)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
diskUsage(dir, info)
}
Sample output :
$ ./diskusage /Users/ | more
Size in bytes : [68] : [/Users//Shared/SC Info]
Size in bytes : [204] : [/Users//Shared]
Size in bytes : [139] : [/Users//sweetlogic/.atom/.apm]
Size in bytes : [402] : [/Users//sweetlogic/.atom/compile-cache/coffee]
Size in bytes : [895] : [/Users//sweetlogic/.atom/compile-cache/cson]
See also : Golang : Read directory content with filepath.Walk()
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
+6.2k Golang : Break string into a slice of characters example
+14.9k Golang : Get HTTP protocol version example
+7.6k Golang : Get today's weekday name and calculate target day distance example
+9.8k Golang : Get login name from environment and prompt for password
+4.4k MariaDB/MySQL : How to get version information
+10.7k Golang : Generate random elements without repetition or duplicate
+29.5k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?
+30.5k Golang : Interpolating or substituting variables in string examples
+18k Golang : Get path name to current directory or folder
+6.3k Golang : Spell checking with ispell example
+23.6k Golang : Use regular expression to validate domain name
+6.3k PHP : Shuffle to display different content or advertisement