简体   繁体   English

使用operator << with boost iostreams压缩过滤器

[英]Using operator<< with boost iostreams compression filters

I am trying to use the boost iostreams compression filters to write to a file using the stream insertion operator (<<). 我试图使用boost iostreams压缩过滤器使用流插入运算符(<<)写入文件。 The name "filtering_ostreambuf" suggests that this should behave as a stream but operator<< is not defined for this class. 名称“filtering_ostreambuf”表示这应该表现为流,但是没有为此类定义operator <<。 Here's some code that obviously doesn't compile. 这里有一些显然无法编译的代码。

#include <boost/iostreams/filter/lzma.hpp>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/device/file.hpp>

namespace io = boost::iostreams;

int main() {

  io::filtering_ostreambuf out;
  io::file_sink ofs("output.xz");
  out.push(ofs);
  out.push(io::lzma_compressor());

  for (int i=0; i<16; ++i) {
    out << i << std::endl;
  }

  return 0;
}

I've tried using a stringstream as a 'source' and using the boost iostreams copy() with it as per the example for the gzip decompression. 我已经尝试使用stringstream作为'source'并使用boost iostreams copy()按照gzip解压缩的示例。 But (1) it doesn't work and (2) even if it did, that seems to be overly verbose to me and doesn't sound like it would be very efficient. 但是(1)它不起作用,(2)即使它确实如此,这对我来说似乎过于冗长,听起来并不是非常有效。

Is there a way to use boost iostreams so that I can just write to a filter chain normally as if it was a stream ? 有没有办法使用boost iostreams,这样我就可以正常写入过滤器链,好像它是一个流? I want to use << not write(). 我想用<< not write()。

That's because you use ostreambuf it's just a stream buffer. 那是因为你使用ostreambuf它只是一个流缓冲区。 stream classes derive from std::basic_ostream and support formatted io "stream" operators (they are actually bit-shift operators). stream类派生自std::basic_ostream并支持格式化的“流”运算符 (它们实际上是位移运算符)。

So this should work: 所以这应该工作:

#include <boost/iostreams/filter/lzma.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/file.hpp>

namespace io = boost::iostreams;

int main() {

  io::filtering_ostream out;
  io::file_sink ofs("output.xz");
  out.push(io::lzma_compressor());
  out.push(ofs);

  for (int i=0; i<16; ++i) {
    out << i << std::endl;
  }

  return 0;
}

At wandbox it fails at linking which is understandable, but compilation itself passes. wandbox中,它在链接时失败,这是可以理解的,但编译本身就会通过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM