Created
April 3, 2017 10:09
-
-
Save zhenwusw/99070caa07f07cd83a6ceb929c1d4be8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"os" | |
"path/filepath" | |
"io/ioutil" | |
"fmt" | |
"flag" | |
) | |
func walkDir(dir string, fileSizes chan<- int64) { | |
for _, entry := range dirents(dir) { | |
if entry.IsDir() { | |
subDir := filepath.Join(dir, entry.Name()) | |
walkDir(subDir, fileSizes) | |
} else { | |
fileSizes <- entry.Size() | |
} | |
} | |
} | |
func dirents(dir string) []os.FileInfo { | |
entries, err := ioutil.ReadDir(dir) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "du1: %v\n", err) | |
return nil | |
} | |
return entries | |
} | |
func printDiskUsage(nfiles, nbytes int64) { | |
fmt.Printf("%d files, %.1f GB\n", nfiles, float64(nbytes)/1e9) | |
} | |
func main() { | |
flag.Parse() | |
roots := flag.Args() | |
if len(roots) == 0 { | |
roots = []string{"."} | |
} | |
fileSizes := make(chan int64) | |
go func() { | |
for _, root := range roots { | |
walkDir(root, fileSizes) | |
} | |
close(fileSizes) | |
}() | |
var nfiles, nbytes int64 | |
for size := range fileSizes { | |
nfiles++ | |
nbytes += size | |
} | |
printDiskUsage(nfiles, nbytes) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment