tags:

views:

2325

answers:

3

Is there a simple way to write binary data into binary file like we used to do in C/C++? For example, how can I create a 4-byte file with serialized 4-byte integer value without using fancy math?

+1  A: 

There are Marshal.dump and Marshal.load methods you can use.

Here's a link: http://en.wikipedia.org/wiki/Serialization#Ruby.

And another that saves the data to a file: http://rubylearning.com/satishtalim/object_serialization.html.

Dave Cluderay
This works ok, but I still couldn't get 4-byte file using this: File.open('test.bin', 'wb') {|file| file << Marshal.dump(12345) }, I'm getting 6-byte file. The problem is that I need to create a binary file of proprietary format, this file consists of records, each of them is fixed-length C-style record with integers, bytes, etc.Thanks for really quick answer though.
Alex Kaushovik
No worries. Pesto's answer looks very promising.
Dave Cluderay
+5  A: 

You can use Array#pack and String#unpack to convert to and from binary representations. Combine them with IO#write and IO#read, and away you go.

Pesto
Yes, I think yours is the better answer for this particular question! +1
Dave Cluderay
Thanks for answer, this worked for me.
Alex Kaushovik
+2  A: 

In my humble oppinion, ruby wasn't made for such tasks. If you have to write to binary files a lot, it would be easiest to write some c functions for that and call them from ruby, which is quite easy using swig. I'm doing the same thing at the moment to write a raid simulator.

Kim
That's right - Ruby was meant for other stuff probably, but we have a pretty big Rails application already and we just faced this need to operate with binary files. Thanks for your answer though - we might consider writing the native extension in C/C++.
Alex Kaushovik