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
2009-06-02 21:02:10
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
2009-06-02 21:13:26
No worries. Pesto's answer looks very promising.
Dave Cluderay
2009-06-02 21:39:22
+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
2009-06-02 21:07:51
Yes, I think yours is the better answer for this particular question! +1
Dave Cluderay
2009-06-02 21:18:29
+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
2009-07-18 07:07:08
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
2009-07-27 17:06:20