Skip to content

Instantly share code, notes, and snippets.

@likai24
Created September 21, 2017 10:47
Show Gist options
  • Save likai24/76615df47c4d6a85dd4889a866a24383 to your computer and use it in GitHub Desktop.
Save likai24/76615df47c4d6a85dd4889a866a24383 to your computer and use it in GitHub Desktop.
read file using go
/*
from https://stackoverflow.com/questions/14514201/how-to-read-a-binary-file-in-go
*/
package main
import (
"fmt"
"io"
"os"
)
func main() {
f, err := os.Open("filename")
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
data := make([]byte, 4096)
zeroes := 0
for {
data = data[:cap(data)]
n, err := f.Read(data)
if err != nil {
if err == io.EOF {
break
}
fmt.Println(err)
return
}
data = data[:n]
for _, b := range data {
if b == 0 {
zeroes++
}
}
}
fmt.Println("zeroes:", zeroes)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment