writing binary file

T

Ted Flethuseo

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
 
J

Joel VanderWerf

Ted said:
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.
NoMethodError: undefined method `pack' for 3:Fixnum
from (irb):1
=> "\003\000\000\000"

And use * for your num array:
=> "\001\000\000\000\002\000\000\000\003\000\000\000"
 
T

Ted Flethuseo

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
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,152
Latest member
LorettaGur
Top