import struct
class CustomStruct:
def __init__(self, id_num, name):
self.id = id_num
self.name = name
def write_struct_to_file(struct_obj, file_path):
with open(file_path, 'wb') as f:
packed_id = struct.pack('!i', struct_obj.id)
name_bytes = struct_obj.name.encode('utf-8')
# 确保name为10个字节,如果不足10个字节,使用空格填充
name_bytes = name_bytes.ljust(10, b' ')
f.write(packed_id)
f.write(name_bytes)
def read_struct_from_file(file_path):
with open(file_path, 'rb') as f:
packed_id = f.read(4)
id_num = struct.unpack('!i', packed_id)[0]
name_bytes = f.read(10)
name = name_bytes.decode('utf-8').rstrip()
return CustomStruct(id_num, name)
# 示例使用
if __name__ == "__main__":
custom_struct = CustomStruct(123, "example")
write_struct_to_file(custom_struct, "test.bin")
read_struct = read_struct_from_file("test.bin")
print(f"ID: {read_struct.id}, Name: {read_struct.name}")
代码解释
- 导入
struct
模块:struct
模块用于处理 C 结构的二进制数据。它提供了 pack
和 unpack
函数,用于将 Python 值转换为 C 结构的二进制表示,以及将二进制数据解析为 Python 值。
- 定义
CustomStruct
类:这是自定义的结构体,包含 id
(int
类型)和 name
(char[10]
类型在 Python 中使用长度为10的字符串模拟)。
write_struct_to_file
函数:
- 以二进制写入模式打开文件。
- 使用
struct.pack('!i', struct_obj.id)
将 int
类型的 id
打包成网络字节序(大端序,由 !
表示)的二进制数据。i
表示 int
类型。
- 将
name
编码为字节串,并使用 ljust
方法确保长度为10个字节,不足则用空格填充。
- 依次将打包后的
id
和处理后的 name
字节串写入文件。
read_struct_from_file
函数:
- 以二进制读取模式打开文件。
- 读取4个字节(
int
类型的大小)作为 packed_id
,然后使用 struct.unpack('!i', packed_id)
解包为 int
类型的 id_num
。
- 读取10个字节作为
name_bytes
,将其解码为字符串,并使用 rstrip
方法去除可能存在的填充空格。
- 返回一个新的
CustomStruct
对象。
- 示例使用:创建一个
CustomStruct
对象,将其写入文件,然后从文件中读取并打印内容,验证写入和读取的准确性。