[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

DANGER ! Ruby-Newbie ahead: How to access binary files

Meino Christian Cramer

1/16/2006 4:45:00 PM

5 Answers

Austin Ziegler

1/16/2006 4:49:00 PM

0

On 16/01/06, Meino Christian Cramer <Meino.Cramer@gmx.de> wrote:
> There is a file on my HD, which was written by a C program. The C
> program wrotes the contents of an array of structures (each array
> element was made from the same structure) to that file.
>
> Since accessing that file looks like a very low level and
> "procedure-based" thing to me I would be very interested how this job
> can be done in a most ruby-like, objectoriented way.

If you're using Windows, make sure you open the file in binary mode:

File.open(filename, "rb") ...

Otherwise, look up Array#unpack. There are examples of this in the
ImageInfo library that is on the RAA; I have a custom copy of it in
PDF::Writer.

-austin
--
Austin Ziegler * halostatue@gmail.com
* Alternate: austin@halostatue.ca


Bob Showalter

1/16/2006 4:51:00 PM

0

Meino Christian Cramer wrote:
> Hi,
>
> There is a file on my HD, which was written by a C program. The C
> program wrotes the contents of an array of structures (each array
> element was made from the same structure) to that file.
>
> Since accessing that file looks like a very low level and
> "procedure-based" thing to me I would be very interested how this job
> can be done in a most ruby-like, objectoriented way.

You need to know the format of the structure and its size.

You can then use IO#read to read bytes from the file into a string and
String#unpack to extract the individual fields from the structure.

Of course, all of this should be encapsulated into a class :-)


Ara.T.Howard

1/16/2006 6:11:00 PM

0

Joel VanderWerf

1/16/2006 9:51:00 PM

0

ara.t.howard@noaa.gov wrote:

> def bar
> @mmap[@offset + Integer::SIZEOF, Float::SIZEOF].unpack("f").first
> end
> def bar= f
> @mmap[@offset + Integer::SIZEOF, Float::SIZEOF] =
> [Float(f)].pack("f")
> end

Doesn't this arithmetic assume that the C compiler is packing the fields
of the struct? What if fields are aligned on 8 byte boundaries, for
instance? I vaguely remember having some issues like this when porting
from x86 to sparc. I guess you could add __attribute__((__packed__)) to
the struct to be sure.

--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407


Ara.T.Howard

1/16/2006 9:59:00 PM

0