How to read a binary file in Go

后端 未结 4 1788
渐次进展
渐次进展 2020-12-15 17:25

I\'m completely new to Go and I\'m trying to read a binary file, either byte by byte or several bytes at a time. The documentation doesn\'t help much and I cannot find any t

4条回答
  •  醉梦人生
    2020-12-15 18:13

    For example, to count the number of zero bytes in a file:

    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)
    }
    

提交回复
热议问题