如何以最佳方式在Nim中编写和读取二进制文件?我想将交替的浮点数和整数写入二进制文件,然后能够读取该文件。在Python中编写这个二进制文件时,我会做类似于以下的操作
import struct
# list of alternating floats and ints
arr = [0.5, 1, 1.5, 2, 2.5, 3]
# here 'f' is for float and 'i' is for int
binStruct = struct.Struct( 'fi' * (len(arr)/2) )
# put it into string format
packed = binStruct.pack(*tuple(arr))
# open file for writing in binary mode
with open('/path/to/my/file', 'wb') as fh:
fh.write(packed)
我会这样做来阅读
arr = []
with open('/path/to/my/file', 'rb') as fh:
data = fh.read()
for i in range(0, len(data), 8):
tup = binStruct.unpack('fi', data[i: i + 8])
arr.append(tup)
在这个例子中,读取文件后,arr会变成:
[(0.5, 1), (1.5, 2), (2.5, 3)]
寻找在Nim中类似的功能。