0
votes

I am trying to use the boost iostreams compression filters to write to a file using the stream insertion operator (<<). The name "filtering_ostreambuf" suggests that this should behave as a stream but operator<< is not defined for this class. 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. 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.

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 ? I want to use << not write().

1

1 Answers

0
votes

That's because you use ostreambuf it's just a stream buffer. stream classes derive from std::basic_ostream and support formatted io "stream" operators (they are actually bit-shift operators).

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.