How to write struct to file in go or python?

huangapple go评论117阅读模式
英文:

How to write struct to file in go or python?

问题

在Go语言中,可以使用encoding/binary包将结构体写入文件。以下是一个示例代码:

  1. package main
  2. import (
  3. "encoding/binary"
  4. "os"
  5. )
  6. type mystruct struct {
  7. i int32
  8. cha byte
  9. }
  10. func main() {
  11. file, err := os.Create("TEST.bin")
  12. if err != nil {
  13. panic(err)
  14. }
  15. defer file.Close()
  16. s := mystruct{
  17. i: 0,
  18. cha: 'A',
  19. }
  20. err = binary.Write(file, binary.LittleEndian, &s)
  21. if err != nil {
  22. panic(err)
  23. }
  24. }

在Python中,可以使用struct模块将结构体写入文件。以下是一个示例代码:

  1. import struct
  2. class MyStruct:
  3. def __init__(self, i, cha):
  4. self.i = i
  5. self.cha = cha
  6. s = MyStruct(0, b'A')
  7. with open('TEST.bin', 'wb') as file:
  8. 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:

  1. #include <stdio.h>
  2. struct mystruct
  3. {
  4. int i;
  5. char cha;
  6. };
  7. int main(void)
  8. {
  9. FILE *stream;
  10. struct mystruct s;
  11. stream = fopen("TEST.$$$", "wb"))
  12. s.i = 0;
  13. s.cha = 'A';
  14. fwrite(&s, sizeof(s), 1, stream);
  15. fclose(stream);
  16. return 0;
  17. }

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语言类似的结构体,并将其转换为字节数组:

  1. import ctypes
  2. class MyStruct(ctypes.Structure):
  3. _fields_ = [('i', ctypes.c_int),
  4. ('cha', ctypes.c_char)]
  5. s = MyStruct()
  6. s.i = 0
  7. s.cha = 'A'
  8. f.write(bytearray(s))

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

  1. import struct
  2. f.write(struct.pack('ic', 0, 'A'))

在Go语言中,可以使用encoding/binary包对结构体进行编码:

  1. type myStruct struct {
  2. i int
  3. cha byte
  4. }
  5. s := myStruct{i: 0, cha: 'A'}
  6. 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:

  1. import ctypes
  2. class MyStruct(ctypes.Structure):
  3. _fields_ = [('i', ctypes.c_int),
  4. ('cha', ctypes.c_char)]
  5. s = MyStruct()
  6. s.i = 0
  7. s.cha = 'A'
  8. 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):

  1. import struct
  2. f.write(struct.pack('ic', 0, 'A'))

Go can encode structs via encoding/binary

  1. type myStruct struct {
  2. i int
  3. cha byte
  4. }
  5. s := myStruct{i: 0, cha:'A'}
  6. 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

huangapple
  • 本文由 发表于 2017年9月10日 17:25:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/46139165.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定