Tutorial

2.1.1. Overview: Devices, stream_buffer and stream

Writing a new stream or stream buffer class using the Boost Iostreams library is easy: you simply write a class modeling the Device concept, then use that class as the template argument to stream or stream_buffer:

#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/stream_buffer.hpp>

namespace io = boost::iostreams;

class my_device { /* */ };

typedef io::stream<my_device>         my_stream;
typedef io::stream_buffer<my_device>  my_streambuf;

Here io::stream_buffer<my_device> is a derived class of std::basic_streambuf, and io::stream<my_device> is a derived class of std::basic_istream, std::basic_ostream or std::basic_iostream depending on the mode of my_device, i.e., depending on which of the fundamental i/o operations read, write and seek it supports.

The template io::stream is provided as a convenience. It's always possible to avoid io::stream and simply use io::stream_buffer together with one of the standard library stream templates. E.g.,

#include <ostream>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/stream.hpp>

namespace io = boost::iostreams;

int main()
{
    io::stream_buffer<io::file_sink> buf("log.txt");
    std::ostream                     out(&buf);
    // out writes to log.txt
}

In this example, the ostream out uses the stream_buffer buf as its underlying data sink, so that data written to out goes to the file log.txt. The same effect could be achieved by default constructing out and telling it to use stream buffer buf by invoking out.rdbuf(&buf).

Another way to define a new stream or stream buffer class using the Boost Iostreams library is to derive from filtering_stream or filtering_streambuf.

The next three items will demonstrate how to write Devices for accessing STL-compatible containers. The source code for the examples can be found in the header <libs/iostreams/example/container_device.hpp>