How to read a binary file in Go

后端 未结 4 1798
渐次进展
渐次进展 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条回答
  •  -上瘾入骨i
    2020-12-15 18:11

    This is what I use to read an entire binary file into memory

    func RetrieveROM(filename string) ([]byte, error) {
        file, err := os.Open(filename)
    
        if err != nil {
            return nil, err
        }
        defer file.Close()
    
        stats, statsErr := file.Stat()
        if statsErr != nil {
            return nil, statsErr
        }
    
        var size int64 = stats.Size()
        bytes := make([]byte, size)
    
        bufr := bufio.NewReader(file)
        _,err = bufr.Read(bytes)
    
        return bytes, err
    }
    

提交回复
热议问题