0

I have one binary file and I want to read this file like first four bytes then next 5 bytes then next 3 bytes till file ends.

I am able to read file using each_byte but I want to categorize all these bytes in groups in sequence they are stored in file.

I am able to read this using following lines but dont know how to read in fixed sized blocks with continutation.

File.open('myfile','rb') do |file|
file.each_byte {|ch| print "#{ch.chr}:#{ch}\t"}

end

Akash Panchal
  • 205
  • 1
  • 6
  • 20

2 Answers2

1

I'm not sure I understand but maybe something like:

file.read.scan(/(.{4})(.{5})(.{3})/).each do |a,b,c|
    puts "first 4 bytes: #{a}"
    puts "bytes 5 to 10: #{b}"
    puts "3 more bytes: #{c}"
end
pguardiario
  • 53,827
  • 19
  • 119
  • 159
  • its near to what I want to do but I want like script prints line "first 4 bytes" then prints contents of first 4 bytes then prints "bytes 5 to 10 " and below it contents of bytes from 5 to 10 and so on till file ends. – Akash Panchal Mar 31 '12 at 12:01
  • ok but what to do if after some fixed sized blocks I want to print rest of variable length blocks how can I print them in one go? I mean what I need to use in regexp instead of /(.{4})/ ? – Akash Panchal Mar 31 '12 at 12:22
  • Also want to print this in hex or some other encoding. – Akash Panchal Mar 31 '12 at 12:55
0

It's not really fast, but it's ruby :-)

file.each_byte.slice_before({pattern: [4,5,3].cycle, left: 0}) do |ele, state|
  if state[:left] == 0
    state[:left] = state[:pattern].next
    true
  else
    state[:left] -= 1
    false
  end
end
Reactormonk
  • 21,472
  • 14
  • 74
  • 123