package main
/*
* Computes md5 sums for files listed on the command line. Similar to the
* Unix md5sum utility. Largely stolen and adapted from an offical Go example.
* https://golang.org/pkg/crypto/md5/#pkg-examples
*/
import (
"crypto/md5"
"fmt"
"os"
"io"
)
func process(fn string) {
// Open the file, print a message and bail if the open fails.
fi, err := os.Open(fn)
if err != nil {
fmt.Println(fn+":",err)
return
}
// Here's a nice use of defer. The file will get closed
// after we're done, whether we leave by error or normally.
defer fi.Close()
// This object accumulates the sum.
h := md5.New()
// We'll copy the data ourselves. (Original uses a higher-level
// call that essentially does all this in one line.)
for {
// Read a block of data from the file.
var data [256]byte
n, err := fi.Read(data[:])
if n == 0 && err == io.EOF {
break
} else if(err != nil) {
fmt.Println(fn+":",err)
return
}
// Write it to the summer. The hash object implements
// a frequently-used interface io.Writer which contains
// the Write method and some others.
h.Write(data[0:n])
}
fmt.Printf("%032x %s\n", h.Sum(nil), fn)
}
func main() {
for _,fn := range(os.Args[1:]) {
process(fn)
}
}