使用boost :: iostreams即时写入压缩数据

时间:2013-06-17 14:39:42

标签: boost-iostreams

我天真的解决方案如下: 创建一个压缩文件缓冲区并将此缓冲区添加到ostream。 但在示例代码中,'output.z'的大小始终为0字节。

#include "boost/iostreams/filtering_streambuf.hpp"
#include "boost/iostreams/filter/zlib.hpp"
#include <iostream>
#include <fstream>

struct MyStruct
{
    MyStruct() : a(3), b("BlaBla"), c(4) {}
    int a;
    const char* b;
    int c;
};

std::ostream& operator << ( std::ostream& out, const MyStruct& in )
{
    return out << in.a << std::endl << in.b << std::endl << in.c;
}

int main ( int argc, char* argv[] )
{
    try {

        {
            boost::iostreams::filtering_ostreambuf sb;

            sb.push (boost::iostreams::zlib_compressor());

            std::string file("output.z");

            std::ofstream device;
            device.open (file.c_str(), std::ios_base::binary);
            if ( device.fail() )
                throw std::runtime_error ( std::string("error opening ") + file );
            sb.push (device);

            std::ostream ls(&sb);

            MyStruct bla;
            ls << bla; 
        }

    }
    catch(boost::iostreams::zlib_error& e)
    {
        std::cout << "Zib error\n";
    }
    catch(...)
    {
        std::cout << "Any other error\n";
    }
}

此示例中的概念错误在哪里?

问候,格特

0 个答案:

没有答案