file compression to handle intermediary output in c++

前端 未结 1 1290
悲&欢浪女
悲&欢浪女 2021-01-15 00:41

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

相关标签:
1条回答
  • 2021-01-15 01:30

    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);
    
    0 讨论(0)
提交回复
热议问题