From: Robert Klemme Date: 2003-12-05T19:32:06+09:00 Subject: Re: how to navigate in a file ? "Mark J. Reed" schrieb im Newsbeitrag news:20031205025328.GA10409@mulan.thereeds.org... > On Fri, Dec 05, 2003 at 01:58:22AM +0100, Boris BXS Schulz wrote: > > Hi, > > > > I would like to open a binary file and read its contents. > > The opening is no problem, but if I wanted to jump to a specific byte, > > how would I do that ? Also, how would I read this specific byte ? I have > > some code reading the byte, but it quite ugly. Is there something like > > DATA.readbyte(position) ? > > What you're looking for is File#seek(offset). For instance: > > foo.rb(main):001:0> # Create a binary file where the byte at position N = N > foo.rb(main):002:0* File.open("binfile", "wb") do > foo.rb(main):003:1* |f| > foo.rb(main):004:1* 256.times do > foo.rb(main):005:2* |b| > foo.rb(main):006:2* f.write(b.chr) > foo.rb(main):007:2> end > foo.rb(main):008:1> end > => 256 > foo.rb(main):009:0> > foo.rb(main):010:0* # Seek to position 128 and read the byte there > foo.rb(main):011:0* File.open("binfile", "rb") do > foo.rb(main):012:1* |f| > foo.rb(main):013:1* f.seek(128) > foo.rb(main):014:1> b = f.getc > foo.rb(main):015:1> puts b > foo.rb(main):016:1> end > 128 > => nil > foo.rb(main):017:0> > Note that for reading and writing "r+b" is the appropriate open mode. File.open("io-test.txt", "r+b") do |io| puts "read" io.seek(0) while ( b = io.read(1) ) printf "%4d 0x%02x %s\n", io.tell, b[0], b.inspect end puts "write" io.seek(0) io.write( "xxx" ) puts "read again" io.seek(0) while ( b = io.read(1) ) printf "%4d 0x%02x %s\n", io.tell, b[0], b.inspect end end Regards robert