提升iostream问题

时间:2011-03-22 04:03:12

标签: c++ boost boost-iostreams

我正在尝试使用以下代码解压缩boost中的gzip字符串

std::string DecompressString(const std::string &compressedString)
{
    std::stringstream src(compressedString);
    if (src.good())
    {
    boost::iostreams::filtering_streambuf<boost::iostreams::input> in(src);
    std::stringstream dst;
    boost::iostreams::filtering_streambuf<boost::iostreams::output> out(dst);
    in.push(boost::iostreams::zlib_decompressor());

    boost::iostreams::copy(in, out);
    return dst.str();
    }
    return "";

}

然而,每当我调用这个函数时(例如下面)

string result = DecompressString("H4sIA");
string result = DecompressString("H4sIAAAAAAAAAO2YMQ6DMAxFfZnCXOgK9AA9ACsURuj9N2wpkSIDootxhv+lN2V5sqLIP0T55cEUgdLR48lUgToTjw/5zaRhBuVSKO5yE5c2kDp5zunIaWG6mz3SxLvjeX/hAQ94wAMe8IAHPCwyMS9mdvYYmTfzdfSQ/rQGjx/t92A578l+T057y1Ff6NW51Uy0h+zkLZ33ByuPtB8IuhdcnSMIglgm/r15/rtJctlf4puMt/i/bN16EotQFgAA");

程序将始终在此行失败

in.push(boost::iostreams::zlib_decompressor());

并生成以下异常

Unhandled exception at 0x7627b727 in KHMP.exe: Microsoft C++ exception: 
boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<std::logic_error> > at memory location 0x004dd868..

我真的不知道这个......有人有什么建议吗?

由于

修改

根据建议,我将代码切换到

 boost::iostreams::filtering_streambuf<boost::iostreams::input> in;//(src);

    in.push(boost::iostreams::zlib_decompressor());
    in.push(src);
     std::stringstream dst;
    boost::iostreams::filtering_streambuf<boost::iostreams::output> out;//(dst);
    out.push(dst);
    boost::iostreams::copy(in, out);

然而,异常仍然发生,除了它现在发生在副本

2 个答案:

答案 0 :(得分:1)

您似乎正在以错误的顺序推送过滤器。

从Boost.Iostreams文档中我可以理解,对于输入,数据按照您按下过滤器的相反顺序流过过滤器。因此,如果您按如下方式更改以下行,我认为它应该工作。

更改

boost::iostreams::filtering_streambuf<boost::iostreams::input> in(src);
std::stringstream dst;
boost::iostreams::filtering_streambuf<boost::iostreams::output> out(dst);
in.push(boost::iostreams::zlib_decompressor());

boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
in.push(boost::iostreams::zlib_decompressor());
in.push(src);        // Note the order of pushing filters into the instream.
std::stringstream dst;
boost::iostreams::filtering_streambuf<boost::iostreams::output> out(dst);

有关详细信息,请阅读Boost.Iostreams Documentation

答案 1 :(得分:1)

遵循brado86的建议后,将zlib_decompressor()更改为gzip_decompressor()