Ger Cas
Ger Cas

Reputation: 2308

Read binary file in chunks of different size with ruby

I'm trying to read a binary file that has chunks of variable size. The size of each chunk is located in a fix position at the beginning of each chunk.

The file is composed like this:

I currently have the code below that extracts main header and chunk header, size and data for first chunk, but I'm quite of novice, and I'm stuck in how to repeat this process for all the chunks.

May somebody help with my case please.

FILENAME="file.bin"

open(FILENAME, "rb") do |z|
    mainheader = z.read(20).unpack('H*')  

    puts mainheader

    puts "############### Chunk No. 1 ######################"

    chunkheader = z.read(16)                                 
    chunksize = z.read(4).unpack('H*')[0].hex
    data = z.read(chunksize).unpack('H*')

    puts chunkheader.unpack('H*')
    puts chunksize
    puts data                    
end

Upvotes: 2

Views: 1248

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

Just surround:

puts "############### Chunk No. 1 ######################"

chunkheader = z.read(16)                                 
chunksize = z.read(4).unpack('H*')[0].hex
data = z.read(chunksize).unpack('H*')

puts chunkheader.unpack('H*')
puts chunksize
puts data 

with loop:

while chunkheader = z.read(16) do
  puts "############### Chunk ######################"
  chunksize = z.read(4).unpack('H*')[0].hex
  data = z.read(chunksize).unpack('H*')

  puts chunkheader.unpack('H*')
  puts chunksize
  puts data 
end

the loop above will be terminated as there is no more data in the file remained. Please note, that the snipped above is in general error-prone, since it expects the file to be not corrupted and will fail if last chunk header reports erroneous amount of bytes.

But in your case it seems to be ok.

Upvotes: 1

Related Questions