Golang : Read binary file into memory
Reading a binary file content into memory for further manipulation is easy with Go. In this tutorial, we will show how to read a binary file into buffer(memory). Go has a standard library package (http://golang.org/pkg/bufio/) to handle this kind of requirement.
The code below will just show you how to read the file content into memory. What you want to do next with the file content is up to you.
readbinaryfile.go
package main
import (
"os"
"bufio"
)
func main() {
file, err := os.Open("binary.dat")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
info, err := file.Stat()
if err != nil {
return nil, err
}
// calculate the bytes size
var size int64 = info.Size()
bytes := make([]byte, size)
// read into buffer
buffer := bufio.NewReader(file)
_,err = buffer.Read(bytes)
}
Reference :
See also : Golang : Read file with ioutil
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+25.5k Golang : dial tcp: too many colons in address
+6.5k Golang : Rename part of filename
+20.6k Golang : Match strings by wildcard patterns with filepath.Match() function
+10k Golang : Create S3 bucket with official aws-sdk-go package
+9.1k Golang : Embed secret text string into binary(executable) file
+14.1k Golang : rune literal not terminated error
+4.9k Javascript : How to replace HTML inside <div>?
+22.2k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+7.9k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+3.8k Nginx and PageSpeed build from source CentOS example
+35.1k Golang : Display float in 2 decimal points and rounding up or down