英文:
How to write struct to file in go or python?
问题
在Go语言中,可以使用encoding/binary
包将结构体写入文件。以下是一个示例代码:
package main
import (
"encoding/binary"
"os"
)
type mystruct struct {
i int32
cha byte
}
func main() {
file, err := os.Create("TEST.bin")
if err != nil {
panic(err)
}
defer file.Close()
s := mystruct{
i: 0,
cha: 'A',
}
err = binary.Write(file, binary.LittleEndian, &s)
if err != nil {
panic(err)
}
}
在Python中,可以使用struct
模块将结构体写入文件。以下是一个示例代码:
import struct
class MyStruct:
def __init__(self, i, cha):
self.i = i
self.cha = cha
s = MyStruct(0, b'A')
with open('TEST.bin', 'wb') as file:
file.write(struct.pack('ci', s.i, s.cha))
这些示例代码将结构体以二进制形式写入文件,确保数据是连续的。在Go中使用encoding/binary
包,而在Python中使用struct
模块。
英文:
In C/C++, we can write a struct to file like this:
#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;
}
But how to wirte a struct to file in go or python ? I want the data in struct are continuous.
答案1
得分: 3
在Python中,你可以使用ctypes
模块来生成与C语言类似的结构体,并将其转换为字节数组:
import ctypes
class MyStruct(ctypes.Structure):
_fields_ = [('i', ctypes.c_int),
('cha', ctypes.c_char)]
s = MyStruct()
s.i = 0
s.cha = 'A'
f.write(bytearray(s))
在Python中,还有一种更简单的方法是使用struct.pack
,并手动提供布局作为第一个参数('ic'
表示一个整数后跟一个字符):
import struct
f.write(struct.pack('ic', 0, 'A'))
在Go语言中,可以使用encoding/binary
包对结构体进行编码:
type myStruct struct {
i int
cha byte
}
s := myStruct{i: 0, cha: 'A'}
binary.Write(f, binary.LittleEndian, &s)
注意:不同的结构体对齐方式、填充方式和字节序可能会有所不同,因此如果你想构建真正可互操作的程序,可以使用特殊的格式,如Google Protobuf。
英文:
In Python you can use ctypes
module which allows you to generate structures with similar layout as C does, and convert them to byte arrays:
import ctypes
class MyStruct(ctypes.Structure):
_fields_ = [('i', ctypes.c_int),
('cha', ctypes.c_char)]
s = MyStruct()
s.i = 0
s.cha = 'A'
f.write(bytearray(s))
There is a simplest approach in Python with using struct.pack
and manually provide a layout as first argument ('ic'
means int
followed by a char):
import struct
f.write(struct.pack('ic', 0, 'A'))
Go can encode structs via encoding/binary
type myStruct struct {
i int
cha byte
}
s := myStruct{i: 0, cha:'A'}
binary.Write(f, binary.LittleEndian, &s)
NOTE: You will be subject of differing structure alignment, padding and endianness, so if you want to build truly interoperable program, use special formats such as Google Protobuf
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论