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

Justin Whear justin at economicmodeling.com
Mon Sep 24 14:57:33 PDT 2012


On Mon, 24 Sep 2012 22:10:04 +0200, TJB wrote:

> Hello,
> 
> I am trying to save some data to compressed binary files.  I have my
> data in a struct, which I can write to a binary file just fine:
> 
> align(1) struct TradesBin {
>    int ttim; int prc;
>    int siz; short g127; short corr; char[2] cond;
>    char ex;
> }
> 
> auto fout = new BufferedFile(outfile, FileMode.Out);
> fout.writeExact(&bin, TradesBin.sizeof);
> 
> Where bin is of type TradesBin, filled with data.  The question is how
> do I now do this with zlib to get compression?
> Suggestions and help are mightily appreciated!
> 
> TJB

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


More information about the Digitalmars-d-learn mailing list