【问题标题】:Using operator<< with boost iostreams compression filters将 operator<< 与 boost iostreams 压缩过滤器一起使用
【发布时间】:2019-05-22 09:33:25
【问题描述】:

我正在尝试使用 boost iostreams 压缩过滤器通过流插入运算符 (

#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;
}

我已经尝试使用 stringstream 作为“源”,并按照 gzip 解压缩的示例使用 boost iostreams copy()。但是(1)它不起作用,并且(2)即使它起作用了,这对我来说似乎过于冗长,听起来也不是很有效。

有没有办法使用 boost iostreams,这样我就可以像写流一样正常写入过滤器链?我想使用

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    那是因为您使用ostreambuf 它只是一个流缓冲区。 stream 类派生自 std::basic_ostream 并支持 formatted io "stream" operators(它们实际上是位移运算符)。

    所以这应该有效:

    #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;
    }
    

    wandbox 链接失败,这是可以理解的,但编译本身通过了。

    【讨论】:

    • 是的,它可以使用 g++ -o compress compress.cpp -std=c++11 -lboost_iostreams -llzma 为我编译链接。
    • 很高兴知道。顺便说一句,按照您的编辑建议,我已经更改了 out 链中的顺序。查看usage examples 似乎文件接收器确实应该是最后一个。抱歉这个错误,但我无法在运行时测试它。干杯。
    猜你喜欢
    • 2014-07-29
    • 1970-01-01
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多