How do I use std.zlib to write a struct of data to a binary file with compression?

Justin Whear justin at economicmodeling.com
Tue Sep 25 13:40:33 PDT 2012


On Tue, 25 Sep 2012 18:08:44 +0000, Justin Whear wrote:

> On Tue, 25 Sep 2012 03:25:37 +0200, TJB wrote:
> 
>>> Since you're already set up with the Stream interface, try creating a
>>> MemoryStream instead of a BufferedFile.  Write to the stream just as
>>> you are now, then use the .data() property (on MemoryStream's
>>> superclass,
>>> TArrayStream) to get an array of raw bytes.  You can feed this array
>>> into the compress function in std.zlib to produce a new (hopefully
>>> shorter)
>>> array of bytes that contains the compressed data.  Simply write this
>>> compressed data to a file with `fout.writeExact(compressed.ptr,
>>> compressed.length)` and you're done.
>>>
>>> Since uncompress works better if you know the exact size of the
>>> uncompressed data, you might also consider writing the uncompressed
>>> size of the data to your output file before the compressed data.
>>>
>>> Justin
>> 
>> Ok, I think I get it.  Can you help me set up the first part,
>> writing to the MemoryStream?
>> 
>> TJB
> 
> I wrote up a quick example program and pasted it here:
>   http://dpaste.dzfl.pl/f1699d07
> 
> Hope that helps you out.

I should point out that in my example, the writing to the MemoryStream is 
not strictly necessary.  I could have simply cast the foo array to an 
array of bytes and passed that into the compress function.  But if you're 
already set up for writing raw data into a stream, the MemoryStream will 
help you minimize code changes as well as facilitate more complex 
scenarios.


More information about the Digitalmars-d-learn mailing list