如何用go或python编写struct到文件?

2024-05-16 11:44:51 发布

您现在位置:Python中文网/ 问答频道 /正文

在C/C++中,我们可以这样编写一个结构:

#include <stdio.h>
struct mystruct
{
    int i;
    char cha;
};

int main(void)
{
    FILE *stream;
    struct mystruct s;
    stream = fopen("TEST.$$$", "wb"))
    s.i = 0;
    s.cha = 'A';
    fwrite(&s, sizeof(s), 1, stream); 
    fclose(stream); 
    return 0;
}

但是如何在go或python中将一个结构wirte到文件中呢?我希望结构中的数据是连续的。在


Tags: teststreamincludemain结构structfileint
1条回答
网友
1楼 · 发布于 2024-05-16 11:44:51

在Python中,您可以使用ctypes模块,该模块允许您生成布局与C类似的结构,并将其转换为字节数组:

^{1}$

Python中有一种最简单的方法,使用struct.pack并手动提供布局作为第一个参数('ic'表示int,后跟一个字符):

^{pr2}$

Go可以通过encoding/binary对结构进行编码

type myStruct struct {
    i int 
    cha byte
}

s := myStruct{i: 0, cha:'A'}
binary.Write(f, binary.LittleEndian, &s)

注意:您将使用不同的结构对齐填充endianness,因此,如果您想构建真正可互操作的程序,请使用特殊格式,如Google Protobuf

相关问题 更多 >