boost库编译及gzip + boost::iostream使用

boost库编译及gzip + boost::iostream使用

一.boost库编译

1.下载源码
http://www.boost.org/users/history/version_1_58_0.html
2.解压文件到本地目录[D:downloadoost_1_58_0],进入目录并运行bootstrap.bat,生成boost相关的构建工具
3.cmd命令编译库
动态库:
bjam install stage --toolset=msvc-12.0 --stagedir="C:Boostoost_vc_120" link=shared runtime-link=shared threading=multi debug release  
静态库:
bjam install stage --toolset=msvc-12.0 --stagedir="C:Boostoost_vc_120" link=static runtime-link=static threading=multi debug release  

注意点:

[1].bjam涉及相关toolset设置,需要时也可修改目录下的project-config.jam,比如添加 using mpi ;[注意mpi后面留有一个空格,然后才是分号]
[2].bjam相关参数说明
--build-dir=<builddir>      编译的临时文件会放在builddir里(这样比较好管理,编译完就可以把它删除了)
--stagedir=<stagedir>       存放编译后库文件的路径,默认是stage
--build-type=complete       编译所有版本,不然只会编译一小部分版本(确切地说是相当于:variant=release, threading=multi;link=shared|static;runtime-link=shared)
link=static|shared          决定使用静态库还是动态库。
threading=single|multi      决定使用单线程还是多线程库。
runtime-link=static|shared  决定是静态还是动态链接C/C++标准库。
--with-<library>            只编译指定的库,如输入--with-regex就只编译regex库了。
--show-libraries            显示需要编译的库名称 

二.编译zlib库

1.下载源码
http://www.zlib.net/fossils/
2.解压文件到本地目录[C:zlib-1.2.8]
3.cmd命令编译库
设置编译库源码路径
set ZLIB_SOURCE="C:zlib-1.2.8"
编译zlib库
bjam install stage --toolset=msvc-12.0 --build-type=complete --stagedir="C:Boostoost_vc_120" threading=multi debug release

三.boost库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> 

std::string strResponse = "boost_gzip_string_test";  
对原数据压缩:
std::string strCompressed;//压缩后数据  
{  
    filtering_ostream fos;
    fos.push(gzip_compressor(gzip_params(gzip::best_compression)));  
    fos.push(boost::iostreams::back_inserter(compressedString));  
    fos << strResponse; 
    boost::iostreams::close(fos);  
}  
对压缩数据进行解压:
std::string decompressedString; //解压后数据
{  
    filtering_ostream fos;  
    fos.push(gzip_decompressor());  
    fos.push(boost::iostreams::back_inserter(decompressedString));  
    fos << strCompressed;    //把压缩数据按容器长度写入流  
    fos << std::flush;
} 

注意点:
服务端返回gzip数据,前两个字节标识为0x1f8b,可通过该标识检测返回的数据是否压缩?

bool IsDataGzipped(std::string strData) const
{
    bool bgziped = false;
    if (strData.size() >= 2
        && static_cast<unsigned char>(strData[0]) == 0x1f
        && static_cast<unsigned char>(strData[1]) == 0x8b)
    {
        bgziped = true;
    }
    
    return bgziped;
}