Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing/reading binary file in Nim

What's the best way to write and read a binary files in Nim? I want to write alternating floats and ints to a binary file and then be able to read the file. To write this binary file in Python I would do something like

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)

To read I would do something like

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)

In this example, after reading the file, arr would be

[(0.5, 1), (1.5, 2), (2.5, 3)] 

Looking for similar functionality in Nim.

like image 833
COM Avatar asked Oct 13 '15 15:10

COM


People also ask

How do you open a binary file for reading?

To open a file in binary format, add 'b' to the mode parameter. Hence the "rb" mode opens the file in binary format for reading, while the "wb" mode opens the file in binary format for writing. Unlike text files, binary files are not human-readable. When opened using any text editor, the data is unrecognizable.

How do you write a binary file?

To write to a binary fileUse the WriteAllBytes method, supplying the file path and name and the bytes to be written. This example appends the data array CustomerData to the file named CollectedData. dat .

Which method is used for writing data in binary file?

dump(): The method used for writing data to binary file is dump() method.


1 Answers

I think you should find everything you need in the streams module. Here is a small example:

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
like image 131
bluenote10 Avatar answered Sep 22 '22 16:09

bluenote10