2011-03-22 55 views
2

我嘗試使用下面的代碼升壓iostream的問題

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 ""; 

} 

然而,解壓縮內部升壓一個gzip壓縮的字符串,每當我打電話到這個函數(如以下)

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); 
然而

,異常仍發生,但它現在發生在副本

回答

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

按照brado86的建議,將zlib_decompressor()更改爲gzip_decompressor()