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
+7.6k Golang : Load DSA public key from file example
+15.8k Golang : Get sub string example
+18.6k Golang : Check whether a network interface is up on your machine
+11.4k Golang : Calculations using complex numbers example
+51k Golang : Check if item is in slice/array
+21k Golang : How to read float value from standard input ?
+9k Golang : Generate random Chinese, Japanese, Korean and other runes
+18.3k Golang : Set, Get and List environment variables
+5.9k Golang : Calculate US Dollar Index (DXY)
+6.6k Golang : How to setup a disk space used monitoring service with Telegram bot
+30.8k Golang : bufio.NewReader.ReadLine to read file line by line
+4.6k JQuery : Calling a function inside Jquery(document) block