Reading a specific offset into a file

Hi all,

What is an easy way to read a specific byte offset of a file? Right
now I’m going through and using the .getc function until I get to the
specific offset I need. This is very tedious because I just have a
list of .getc calls. THere must be an easier way to do this?

Right now I’m doing this in order to get to 4th byte in file:

···

a = File.open(“example.dat”)
a.getc
a.getc
a.getc
a.getc
byte_4 = a.getc
a.close

Thanks,

  • Khurram

What is an easy way to read a specific byte offset of a file? Right
now I'm going through and using the .getc function until I get to the
specific offset I need. This is very tedious because I just have a
list of .getc calls. THere must be an easier way to do this?

See the method IO#seek

   http://www.rubycentral.com/ref/ref_c_io.html#seek

Guy Decoux

You could use a loop:

a = File.open(“example.dat”)
4.times { a.getc }
byte_4 = a.getc
a.close

:wink:

Of course, IO#seek is what you really need, or possibly even
IO#read/String#unpack.

T

···

In article 9ba6a8da.0209100651.449803e8@posting.google.com, Khurram wrote:

What is an easy way to read a specific byte offset of a file? Right
now I’m going through and using the .getc function until I get to the
specific offset I need. This is very tedious because I just have a
list of .getc calls. THere must be an easier way to do this?

Right now I’m doing this in order to get to 4th byte in file:

a = File.open(“example.dat”)
a.getc
a.getc
a.getc
a.getc
byte_4 = a.getc
a.close

Thanks,

  • Khurram