A simple Go Program to display file names and file size in human readable format.
I have used flags, path/filepath and bytefmt packages to achieve the necessary output.
Packages used
flags package: Command-line parsing.
path/filepath package: traverse or manipulate the filename paths.
bytefmt package: Human-readable byte formatted.
Before proceeding to the execution of the program, make sure to download the dependency.
go get -u code.cloudfoundry.org/bytefmt
package main
import (
"path/filepath"
"os"
"flag"
"fmt"
"code.cloudfoundry.org/bytefmt"
)
func walkpath(path string, f os.FileInfo, err error) error {
//fmt.Printf("%s with %d bytesn", path,f.Size())
fmt.Printf("%s with %s n", path,bytefmt.ByteSize(uint64(f.Size())))
return nil
}
func main() {
flag.Parse()
root := flag.Arg(0) // 1st argument is the directory location
filepath.Walk(root, walkpath)
}
Output
C:UserskarthikgitgithubGosrckarthikworld>go run readdirwalk.go ./
./ with 4K
CoreOS- etcd 2.0.mp4 with 241.6M
employee.txt with 218B
readdirwalk.go with 471B
reverse-test.go with 309B
C:UserskarthikgitgithubGosrckarthikworld>go run readdirwalk.go .
. with 4K
CoreOS- etcd 2.0.mp4 with 241.6M
employee.txt with 218B
readdirwalk.go with 471B
reverse-test.go with 309B
Tip: To install Go projects and download all the dependencies in one shot
go get ./...