writing/reading Nim 中的二进制文件

writing/reading binary file in Nim

在 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 中寻找类似的功能。

我认为您应该在 streams 模块中找到您需要的一切。这是一个小例子:

import streams

type
  Alternating = seq[(float, int)]

proc store(fn: string, data: Alternating) =
  var s = newFileStream(fn, fmWrite)
  s.write(data.len)
  for x in data:
    s.write(x[0])
    s.write(x[1])
  s.close()

proc load(fn: string): Alternating =
  var s = newFileStream(fn, fmRead)
  let size = s.readInt64() # actually, let's not use it to demonstrate s.atEnd
  result = newSeq[(float, int)]()
  while not s.atEnd:
    let element = (s.readFloat64.float, s.readInt64.int)
    result.add(element)
  s.close()


let data = @[(1.0, 1), (2.0, 2)]

store("tmp.dat", data)
let dataLoaded = load("tmp.dat")

echo dataLoaded