在Nim中写/读二进制文件

时间:2015-10-13 15:58:21

标签: io binaryfiles 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中寻找类似的功能。

1 个答案:

答案 0 :(得分:9)

我认为您应该在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