Reading binary files (or strings)


(Nobuyoshi Nakada) #1

Hi,

or:
iostream.unpack(format) ## not found either.

You can use StringIO.
:pserver:anonymous@cvs.ruby-lang.org:/src/rough/ext/stringio/

or included in 1.7

I found that a bit hard to figure out. The comments in stringio.rb
seem to be
all Japanese, and stringio.c in 1.7 isn’t commented (or documented) at all

Sorry, I’ve written nothing other than TestStringIO.rb in
rough/ext/stringio.

Since it doesn’t have #unpack:

require ‘stringio’

class Dotqread
def initialize(fn)
@blob = StringIO.new(File.open(fn) {|f| f.read})
end
def wordread
@blob.read(2).unpack(“s”)[0]
end
def longread
@blob.read(4).unpack(“L”)[0]
end
def txtread
Opstring.new(@blob.read(wordread))
end
end

···

At Sat, 1 Jun 2002 22:46:30 +0900, Han Holl wrote:


Nobu Nakada


(Han Holl) #2

Since it doesn’t have #unpack:

require ‘stringio’

class Dotqread
def initialize(fn)
@blob = StringIO.new(File.open(fn) {|f| f.read})
end
def wordread
@blob.read(2).unpack(“s”)[0]
end
def longread
@blob.read(4).unpack(“L”)[0]
end
def txtread
Opstring.new(@blob.read(wordread))
end
end

It certainly looks nicer than
def wordread
a = @blob.unpack("@#{@offset}s")[0]
@offset += 2
a
end
or
def wordread
@offset += 2
@blob.unpack("@#{@offset - 2}s")[0]
end

but as far as I can see, you have to check for EOF before each
{word|long|txt}read,
or you risk calling nil.unpack() ?

Cheers

Han


(Nobuyoshi Nakada) #3

Hi,

···

At Sun, 2 Jun 2002 19:16:59 +0900, Han Holl wrote:

but as far as I can see, you have to check for EOF before each
{word|long|txt}read,
or you risk calling nil.unpack() ?

It was just a quick example. You can use readbytes.rb to
ensure data to be read.


Nobu Nakada