Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a struct as binary data to a file in golang?

Tags:

file

binary

go

What is the golang equivalent of the following C code ?

fwrite(&E, sizeof(struct emp), n, f);

I tried using

[]byte(i)

to convert it, but that won't work, it seems.

like image 775
sixter Avatar asked Dec 05 '22 11:12

sixter


1 Answers

You can use "encoding/binary" package:

import "encoding/binary"

func dump() {
    f, err := os.Create("file.bin")
    if err != nil {
        log.Fatal("Couldn't open file")
    }
    defer f.Close()

    var data = struct {
        n1 uint16
        n2 uint8
        n3 uint8
    }{1200, 2, 4}
    err = binary.Write(f, binary.LittleEndian, data)
    if err != nil {
        log.Fatal("Write failed")
    }
}
like image 144
rayed Avatar answered Dec 20 '22 19:12

rayed