How to Read and Write Binary Files in Go

Read and write raw bytes to files in Go using os.Open, os.Create, and io.ReadFull.

Use os.Open or os.Create to get a file handle, then use io.ReadFull or io.Copy to read bytes and file.Write to write bytes.

package main

import (
	"fmt"
	"io"
	"os"
)

func main() {
	// Write binary data
	data := []byte{0x00, 0x01, 0x02, 0xFF}
	f, err := os.Create("binary.bin")
	if err != nil {
		fmt.Println(err)
		return
	}
	_, err = f.Write(data)
	f.Close()

	// Read binary data
	f, err = os.Open("binary.bin")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()

	buf := make([]byte, 4)
	_, err = io.ReadFull(f, buf)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("Read: %v\n", buf)
}