Writing binary file

Hi everyone,

I'm trying to write a couple of numbers to a binary file:

num = [1234567, 30, 40]
File.open("test.file", "wb") { |f|
  num.each { |e| f.write e.to_i.pack("I") }
  # f.write num.pack("I")
}

a = []
File.open("test.file", "rb") { |f|
  a = f.read(4).unpack("I")
  puts a
}

but I get errors for pack, I'd like to be able to use it such that I can
read
write several integers to binary file. I have seen it work for this code
(but it is only one int):

num = [1234567]
File.open("test.file", "wb") { |f|
  num.each { |e| f.write e.to_i.pack("I") }
  # f.write num.pack("I")
}

a = []
File.open("test.file", "rb") { |f|
  a = f.read(4).unpack("I")
  puts a
}

Any help appreciated.
Ted

···

--
Posted via http://www.ruby-forum.com/.

Ted Flethuseo wrote:

Hi everyone,

I'm trying to write a couple of numbers to a binary file:

num = [1234567, 30, 40]
File.open("test.file", "wb") { |f|
  num.each { |e| f.write e.to_i.pack("I") }

you gotta put the integers in an array.

>> 3.pack "I"
NoMethodError: undefined method `pack' for 3:Fixnum
  from (irb):1
>> [3].pack "I"
=> "\003\000\000\000"

And use * for your num array:

>> [1,2,3].pack "I*"
=> "\001\000\000\000\002\000\000\000\003\000\000\000"

Cool, it works well, but I would like to read x integers at a time.
because the files I might read can be pretty large.

I also tried to read a binary file in a computer with linux. So I copied
my binary file and the binreader script onto that computer. Ran it, and
got completely different numbers.

a = Array.new
File.open(inFile, "rb") { |f|
  a = f.read.unpack("I*")
  puts a
}

···

--
Posted via http://www.ruby-forum.com/.