I want to compress a intermediate output of my program ( in C++) and then decompress it.
Asked
Active
Viewed 3,594 times
3
-
possible duplicate of [fastest c++ file compression library available?](http://stackoverflow.com/questions/124239/fastest-c-file-compression-library-available) – Oliver Charlesworth Apr 14 '12 at 18:30
-
Why not use zlib ? Light, efficient and very widely used. – Raveline Apr 14 '12 at 18:36
1 Answers
11
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);
-
That was of great help. How do I serve the location of the file I want to compress instead of text ? Thanks – user1309369 Apr 14 '12 at 23:35
-
@user1309369: Can you clarify? Do you have an existing file that you want to compress? Or? – Anonymous Apr 15 '12 at 08:33
-
I want to compress an existing file and then decompress it when I need it in original format. – user1309369 Apr 15 '12 at 22:44