如何将结构作为二进制数据写入golang中的文件? [英] How to write a struct as binary data to a file in golang?

查看:600
本文介绍了如何将结构作为二进制数据写入golang中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆