I want to read binary file inNim-language. Because I want to work with WAV files.
But I don't know how easy it is to read the first four bytes. This may be because I am not good at English.
I wrote the following code. However, nil is displayed.
var hFile = open("example.wav", FileMode.fmWrite)
# RIFF
var buffer: pointer
echo readBuffer(hFile, buffer, 4)
echo repr(buffer)
How do I handle binary files? I would appreciate it if you could tell me.
Your buffer points to nothing, allocate an array[4, byte] and pass its address to readBuffer.
I suggest you use streams if you need to save your position/restart your processing.
For example this is how I read the first 6 bytes for a magic string for a binary format.
proc read_npy*[T: SomeNumber](npyPath: string): Tensor[T] {.noInit.} =
if unlikely(not existsFile(npyPath)):
raise newException(IOError, &".npy file \"{npyPath}\" does not exist")
let stream = newFileStream(npyPath, mode = fmRead)
defer: stream.close()
# Check magic string
var magic_string: array[6, char]
discard stream.readData(magic_string.addr, 6)
doAssert magic_string == ['\x93', 'N', 'U', 'M', 'P', 'Y'],
"This file is not a Numpy file"
Here is my code that reads wave files:
https://github.com/treeform/euphony/blob/master/src/euphony/wav.nim
There i use newFileStream which makes reading binary files really easy. Just use readStr, readUint16, readUint32...
Wave happens to be a really easy format to read. Just a small header and big chunk of data.
If you also want to play files use the rest of the sound library for that:
https://github.com/treeform/euphony
Note: Your code should also work with the readBuffer but I think you opened the file for writing with FileMode.fmWrite.
Thank you for your reply! And thank you for your source code! I try to study by your code.
Thank you for your reply!
Your buffer points to nothing, allocate an array[4, byte] and pass its address to readBuffer. Oh I must allocate read buffer size...I see.
For example this is how I read the first 6 bytes for a magic string for a binary format.
Thank you your sample code! I saw ”stream” for the first time. I try to study!
Thank you!