我正在使用boost iostreams(1.64.0)来解压zlib数据。 我希望进行流式解压缩。这意味着压缩数据大小是不可预测的。 我编写了以下示例代码。
#include <sstream>
#include <string>
#include <iostream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/zlib.hpp>
int main() {
// Compress
std::stringstream sender;
boost::iostreams::filtering_streambuf<boost::iostreams::input> out;
out.push(boost::iostreams::zlib_compressor());
out.push(sender);
sender << "Hello World";
std::stringstream compressed;
boost::iostreams::copy(out, compressed);
// Decompress
boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
in.push(boost::iostreams::zlib_decompressor());
in.push(compressed);
std::istream is(&in);
std::size_t const buf_size = 256;
char buf[buf_size] = { '\0' };
#if 0
is.getline(buf, buf_size); // works fine
#else
std::size_t read_size = is.readsome(buf, buf_size);
std::cout << "read_size:" << read_size << std::endl;
#endif
// http://www.cplusplus.com/reference/ios/ios/rdstate/
std::cout << "rdstate:" << is.rdstate() << std::endl;
std::cout << buf << std::endl;
}
我使用
readsome()
函数,因为数据的大小是不可预测的。
我得到了以下输出:read_size:0
rdstate:0
这对我来说是出乎意料的。
如果我使用getline()
而不是readsome()
,我会得到以下输出:
rdstate:2
Hello World
这是预期输出。
我认为当我使用 readsome()
时,输出应该是相同的。
因为原始数据是二进制格式,所以我无法在实际代码中使用 getline()
。
有没有办法在使用 filtering_streambuf
或者其他好的方法流式解压不确定长度的二进制数据时使用 readsome()
?
read()
呢? - seheistream :: read()
和istream :: readsome()
的行为,它们的行为类似于boost asio
的read()
和socket :: read_some()
。我用以下代码进行了替换:`is.read(buf, buf_size);` `std::size_t read_size = is.gcount();` `std::cout << "read_size:" << read_size << std::endl;`
然后我的代码就按照我预期的那样工作了。 - Takatoshi Kondo