#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");
}
学习笔记:gzip + boost::iostream
最新推荐文章于 2024-03-13 20:19:32 发布