parsing - Reading binary byte by byte in Ruby -


i'm trying read binary file in chunks, , solution far has been this:

first_portion = file.binread(replay_file, 20) second_portion = file.binread(replay_file, 24, 20) 

where first number amount of bytes read , second offset.

i know bad because file.binread closes file each time after returning. how can open file once, with is, close when i'm done (but still use binread).

also, small question. i've been looking @ few examples of in python , seen this:

uint32 = 'uintle:32'  length = binary_file.read(uint32) content = binary_file.read(8 * length) 

what doing (how work), , in ruby?

you can open file , read bytes in chunks #read , #seek:

file.open(replay_file) |file|   first_portion = file.read(20)   file.seek(24, io::seek_end)   second_portion = file.read(20) end 

the file closed automatically in end.

about second question, i'm not python expert, , correct me if i'm wrong, in ruby:

length = binary_file.read(4).unpack('n').first # 32 bits = 4 bytes # i.e., read 4 bytes, convert 32 bit integer, # fetch first element of array (unpack returns array)  content = binary_file.read(8 * length) # pretty verbatim 

you can check more options here: string#unpack