问题描述

以下C代码的golang等效项是什么?

What is the golang equivalent of the following C code ?

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

我尝试使用

[]byte(i)

进行转换,但这似乎行不通.

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

推荐答案

您可以使用"encoding/binary"包:

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")
    }
}

这篇关于如何将结构作为二进制数据写入golang中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!