学习笔记:gzip + boost::iostream

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

#include <vector>
#include <string>
#include <iostream>
#include <sstream>

using namespace boost::iostreams;

template<typename T>
std::ostream &operator <<(std::ostream &os, const std::vector<T> &v) {
    using namespace std;
    copy(v.begin(), v.end(), ostream_iterator<T>(os));
    return os;
}

void test1()
{
    std::string OriginalString = "hello world";

    std::vector<char> CompressedVector;
    {
        filtering_ostream fos;    //具有filter功能的输出流
        fos.push(gzip_compressor(gzip_params(gzip::best_compression)));  //gzip压缩功能
        fos.push(boost::iostreams::back_inserter(CompressedVector));     //输出流的数据的目的地
        fos << OriginalString;
        boost::iostreams::close(fos);  //flush to CompressedVector 此函数调用后,CompressedVector存储的是gzip压缩后的数据
    }

    std::string decompressedString;
    {
        filtering_ostream fos;
        fos.push(gzip_decompressor());  //gzip解压缩功能
        fos.push(boost::iostreams::back_inserter(decompressedString)); //存放流的数据的目的地
        fos.write(CompressedVector.data(), CompressedVector.size()); //把压缩的数据写入流
        // 或者用如下的形式。需要自定义(ostream<<vector)运算符 
        //out << compressedVector;
        boost::iostreams::close(fos); //flush. decompressedString中出现解压后的数据
    }

    if ( OriginalString == decompressedString) {
        std::cout << "test1() OK" << std::endl;
    }
}

void test2()
{
    std::string OriginalString = "hello world";

    std::string compressedString;
    {
        filtering_ostream fos;    //具有filter功能的输出流
        fos.push(gzip_compressor(gzip_params(gzip::best_compression)));
        fos.push(boost::iostreams::back_inserter(compressedString));
        fos << OriginalString;   //把压缩的数据写入流
        boost::iostreams::close(fos);  //flush. compressedString出现压缩后的数据
                                       //此时,不应当把string当做字符串理解,应该理解为一个char容器
    }

    std::string decompressedString;
    {
        filtering_ostream fos;
        fos.push(gzip_decompressor());
        fos.push(boost::iostreams::back_inserter(decompressedString));

        fos << compressedString; //把压缩数据写入流。此处,不会理会char=0的字节,只按照容器长度写入流。
                                 //strlen(compressedString.c_str() != compressedString.size())

        fos << std::flush;  //compressedString出现压缩后的数据
        
    }

    if (OriginalString == decompressedString) {
        std::cout << "test2() OK" << std::endl;
    }
}

int main() 
{
    test1();
    test2();
    system("pause");
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值