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
+15.9k Golang : Create and resolve(read) symbolic links
+7.3k Golang : flag provided but not defined error
+17k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+11k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+4.3k Golang : Check if password length meet the requirement
+3.8k Unix/Linux : How to open tar.gz file ?
+10.7k Golang : Tutorial on loading GOB and PEM files
+22.6k Golang : Convert CSV data to JSON format and save to file
+4.5k Golang : Muxing with Martini example
+29.9k Golang : Display float in 2 decimal points and rounding up or down
+5.5k Golang : Generate Datamatrix barcode
+8k Golang : Convert decimal number(integer) to IPv4 address