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.
  1. Download and unarchive the tarball into a folder gzstream.
  2. Type "cd gzstream" and then "make" at the command prompt. It should make a library called "libgzstream.a"
  3. Move the folder to an appropriate location if needed.
  4. In the C++ program file: #include the headers gzstream.h, iostream, and fstream.
  5. 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.
  6. Write to the file using somthing that may look like "rpout << setprecision(4) << sigma << endl;"
  7. Close the file with "rpout.close();"
  8. 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.
  9. You are now good to go, with "a.out".

No comments: