Main Page   Class Hierarchy   Compound List   File List   Compound Members   File Members  

Bz2 Stream Classes

bz2stream is a set of four classes making it easy to use the bz2 compression algorithm from C++. The four classes are two stream buffers -- one for compression and one for decompression -- and two streams -- one for input and one for output.

The input stream uses the decompression stream buffer, and the output stream uses the compression stream buffer; this makes it possible to read from a bz2 input stream just as you would read from std::cin or from a std::ifstream, and to write to a bz2 output stream just the way you would write to any other output stream, like std::cout or a std::ofstream without worrying about compression and decompression at all.

The streams do not write the data to any default destination, but to another stream buffer. This gives you the maximun possible flexibility. You just create a "normal" input or output stream, and then use pass its stream buffer to the bz2 stream. The bz2 stream acts as a filter, compressing or decompressing all the data you pass it.

For example, to read a file, compress it and write it to another file a program as the following would be enough:

    #include "bz2stream.hpp"
    #include <iostream>
    #include <fstream>
   
    int main(int argc, char** argv) {
        std::ifstream infile(argv[1], std::ios::binary);
        std::ofstream outfile(argv[2], std::ios::binary);
        bz2ostream out(outfile.rdbuf());
        out << infile.rdbuf();
    }

The performance loss because of the use of the stream classes and not of direct calls to libbzip2's API is virtually non existent. This small program is as fast as bzip2. There is a bit a more extensive test program included in the archive.

Notice that the stream buffer you pass to the bz2istream or bz2ostream constructor must be in binary mode, because the compressed data is binary and the conversions which happen in text mode will corrupt it.

The use of the bz2 stream classes is especially easy because there are no libraries you need to link to; you only need to include the bz2stream.hpp header. (Of course you must link against libbz2).

Notice that this is an early release; this code is tested, but not ready for applications where absolute reliability is a must.


Generated on Sat Jul 6 15:18:45 2002 for bz2stream by doxygen1.2.16