I'm currently trying to read a binary file in chunks, and my solution so far has been this:
first_portion = File.binread(replay_file, 20)
second_portion = File.binread(replay_file, 24, 20)
Where the first number is the amount of bytes to read and the second is the offset.
I know this is bad because File.binread closes the file each time after returning. How can I open the file once, do what I with with is, then close it when I'm done (but still use binread).
Also, another small question. I've been looking at a few examples of this in python and seen this:
UINT32 = 'uintle:32'
length = binary_file.read(UINT32)
content = binary_file.read(8 * length)
What exactly is this doing (how does it work), and what would this look like in Ruby?
You can open the file and read bytes in chunks with #read
and #seek
:
File.open(replay_file) do |file|
first_portion = file.read(20)
file.seek(24, IO::SEEK_END)
second_portion = file.read(20)
end
The file is closed automatically in the end
.
About the second question, I'm not a Python expert, and someone correct me if I'm wrong, but it would be this in Ruby:
length = binary_file.read(4).unpack('N').first
# 32 bits = 4 bytes
# i.e., read 4 bytes, convert to a 32 bit integer,
# fetch the first element of the array (unpack always returns an array)
content = binary_file.read(8 * length)
# pretty much verbatim
You can check more options here: String#unpack
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With