user1309369
user1309369

Reputation: 35

file compression to handle intermediary output in c++

I want to compress a intermediate output of my program ( in C++) and then decompress it.

Upvotes: 3

Views: 3912

Answers (1)

Anonymous
Anonymous

Reputation: 18631

You can use Boost IOStreams to compress your data, for example something along these lines to compress/decompresses into/from a file (example adapted from Boost docs):

#include <fstream>
#include <iostream>

#include <boost/iostreams/filtering_stream.hpp>    
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>

namespace bo = boost::iostreams;

int main() 
{
    {
    std::ofstream ofile("hello.gz", std::ios_base::out | std::ios_base::binary);
    bo::filtering_ostream out;
    out.push(bo::gzip_compressor()); 
    out.push(ofile); 
    out << "This is a gz file\n";
    }

    {
    std::ifstream ifile("hello.gz", std::ios_base::in | std::ios_base::binary);
    bo::filtering_streambuf<bo::input> in;
    in.push(bo::gzip_decompressor());
    in.push(ifile);
    boost::iostreams::copy(in, std::cout);
    }
}

You can also have a look at Boost Serialization - which can make saving your data much easier. It is possible to combine the two approaches (example). IOStreams support bzip compression as well.

EDIT: To address your last comment - you can compress an existing file... but it would be better to write it as compressed to begin with. If you really want, you could tweak the following code:

std::ifstream ifile("file", std::ios_base::in | std::ios_base::binary);
std::ofstream ofile("file.gz", std::ios_base::out | std::ios_base::binary);

bo::filtering_streambuf<bo::output> out;
out.push(bo::gzip_compressor());
out.push(ofile); 
bo::copy(ifile, out);

Upvotes: 11

Related Questions