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
+12.9k Android Studio : Use image as AlertDialog title with custom layout example
+12.6k Golang : Check if an integer is negative or positive
+13.3k Golang : ROT47 (Caesar cipher by 47 characters) example
+6.6k Golang : Convert(cast) io.Reader type to string
+22.9k Golang : How to validate URL the right way
+5.3k Golang & Javascript : How to save cropped image to file on server
+12.7k Golang : How to check if a file is hidden?
+6.5k Golang : Lock executable to a specific machine with unique hash of the machine
+15k Golang : Generate QR codes for Google Authenticator App and fix "Cannot interpret QR code" error
+4k Javascript : How to get width and height of a div?
+12.6k Golang : Human readable time elapsed format such as 5 days ago