Created
September 21, 2017 10:47
-
-
Save likai24/76615df47c4d6a85dd4889a866a24383 to your computer and use it in GitHub Desktop.
read file using go
This file contains 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
/* | |
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