On Tue, 23 Oct 2001, Martin Kahlert wrote:

> Hi!

> I want to read a file containing double values in binary representation,
> i.e. they have been written from C using
> 
> double variable;
> write(fd, &variable, sizeof(variable));
> 
> How can i read this file from ruby and stuff the data into a ruby double
> variable? (The file has been built on the same machine, so endianess should
> not be a problem).
> 
This should be self-explanatory:

def file_exists?(filename)
  test(?f, filename)
end

def read_file(filename)
  File.open(filename, "r") do |f|
    f.read.unpack("d*")
  end
end

def write_file(filename, doubles)
  File.open(filename, "w") do |f|
    f.write(doubles.pack("d*"))
  end
end

if file_exists?(ARGV[0])
  doubles = read_file(ARGV[0])
  p doubles
else
  write_file(ARGV[0], [1.2, -9.8e10, 3.45e-32])
end

Regards,

Robert