Saturday, September 17, 2011

How to write gzipped files from a C++ program?

Every so often, you write a C++ program that generates a ton of output. There are cases when you want to write continuously to a compressed gzipped file from the C++ program (rather than using gzip to compress a large file after the program has finished running).

One solution is to use the gzstream library. It "is a small C++ library, basically just a wrapper, that provides the functionality of the zlib C-library in a C++ iostream. It is freely available under the LGPL license."

How do you actually do it? It is actually quite simple in a standard *nix system.

Type "cd gzstream" and then "make" at the command prompt. It should make a library called "libgzstream.a"

Move the folder to an appropriate location if needed.

In the C++ program file: #include the headers gzstream.h, iostream, and fstream.

In your C++ program, say "ogzstream rpout("sigma.gz");", where rpout is the handle and sigma.gz is the filename that you want to write to.

Write to the file using somthing that may look like "rpout << setprecision(4) << sigma << endl;"

Close the file with "rpout.close();"

Finally to compile the C++ program say something like: "g++ program.cpp -I./gzstream -L./gzstream -lz -lgzstream". Here I assume that the gzstream directory is located in the same directory as the C++ program. If this is not true, then you have to change the -I and -L location tags.