10

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.

1
  • 1
    It would be bad in C too, why would you want that in go then? Commented Jul 12, 2018 at 7:47

2 Answers 2

21

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")
    }
}
Sign up to request clarification or add additional context in comments.

Comments

7

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

5 Comments

Precisely. @sixter, note that your 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.
you could always use unsafe.uintptr and unsafe.Sizeof to do the exact thing as in C but as everyone here is saying, it's asking for trouble.
There are situations when you need to deal with binary data, and where the compatibility/standards/endianness are not an issue. This answer can be a good contribution in case that the OP does not know that Gob/JSON/XML and the original need can be fulfiled with those ones, but by no means is valid for the scenarios where binary is needed to get the required throughput or performance. In such cases proposing JSON/XML is totally wrong.
You should 100% serialize to binary if you are writing a binary file. Binary formats, erm, pre-exist in the world, you know, and they can be modeled by structs.
This is bad advice. In C/C++, you write to file in bytes, by specifying a pointer and size. The same should be feasible in Go. After all, even the underyling serializer ends up writing the data in binary format anyway. I do not see a problem here. There are moments when you need to read file headers (PE, ZIP, PNG, JPEG, MP3, etc)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.