Video Coming Soon...
38: stat Then du
This exercise is pending. Quick notes about this exercise:
- My implemention is at https://lcthw.dev/go/go-coreutils
- https://www.gnu.org/software/coreutils/manual/html_node/du-invocation.html
- os -- https://pkg.go.dev/os@go1.25.3
- path -- probably all of them use it
- regex -- https://pkg.go.dev/regexp@go1.25.3
The stat Code
View Source file go-coreutils/stat/main.go Only
package main
import (
"fmt"
"os"
"flag"
"log"
"io/fs"
)
func PrintStat(stat fs.FileInfo) {
fmt.Printf("File: %s\nSize: %d\nAccess: %v\nModify: %v",
stat.Name(),
stat.Size(),
stat.Mode(),
stat.ModTime())
}
func main() {
flag.Parse()
files := flag.Args()
for _, fname := range files {
f, err := os.Open(fname)
if err != nil { log.Fatal(err) }
defer f.Close()
stats, err := f.Stat()
if err != nil { log.Fatal(err) }
PrintStat(stats)
}
}
The du Code
View Source file go-coreutils/du/main.go Only
package main
import (
"fmt"
"log"
"flag"
"io/fs"
"path/filepath"
)
func StatDir(target_path string) error {
var cur_dir string
var cur_size int64
// NOTE: cover the difference betweeen filepath.WalkDir and fs.WalkDir
err := filepath.WalkDir(target_path, func (path string, d fs.DirEntry, err error) error {
if d.IsDir() {
if cur_dir != path {
loc := filepath.Join(target_path, cur_dir)
fmt.Printf("%s %d\n", loc, cur_size / 1024)
cur_dir = path
cur_size = 0
}
} else {
info, err := d.Info()
if err != nil { return nil }
cur_size += info.Size()
}
return nil
})
return err
}
func main() {
flag.Parse()
paths := flag.Args()
for _, path := range paths {
err := StatDir(path)
if err != nil { log.Fatal(err) }
}
}
Register for Learn Go the Hard Way
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.