gpt4 book ai didi

io - 在 Nim 中写入/读取二进制文件

转载 作者:行者123 更新时间:2023-12-04 02:09:35 25 4
gpt4 key购买 nike

在 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

关于io - 在 Nim 中写入/读取二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33107332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com