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.
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.
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")
}
}
You should not do that, just use a serialization format that supports automatic serialization and deserialization. Go's standard library supports:
Gob: go binary encoding of structs. Recommended when you're not interested in interchange with other languages. https://golang.org/pkg/encoding/gob/
JSON: Welp, you know... If you need to exchange serialized data with other languages. https://golang.org/pkg/encoding/json/
XML: If you're feeling retro.
And of course protobuf is another option to consider, if you want type safe interchange with other languages, which json doesn't support. https://github.com/golang/protobuf
fwrite call is broken: the exact format to be written this way depends on the endianness of the underlying H/W and on the padding the compiler picked for your struct (and the crap in the padding spaces will be written as well). And it also depends on the sizes of some special types like int or size_t if you had used them. (In go, int and uintptr also have different sizes on different arches.) If you really need hand-crafted binary serialization, see the stock encoding/binary package.