title: How to write custom input stream in C++
body: <p>I'm currently learning C++ (Coming from Java) and I'm trying to understand how to use IO streams properly in C++. </p>
  
  <p>Let's say I have an <code>Image</code> class which contains the pixels of an image and I overloaded the extraction operator to read the image from a stream:</p>
  
  <pre><code>istream&amp; operator&gt;&gt;(istream&amp; stream, Image&amp; image)
  {
      // Read the image data from the stream into the image
      return stream;
  }
  </code></pre>
  
  <p>So now I'm able to read an image like this:</p>
  
  <pre><code>Image image;
  ifstream file("somepic.img");
  file &gt;&gt; image;
  </code></pre>
  
  <p>But now I want to use the same extraction operator to read the image data from a custom stream. Let's say I have a file which contains the image in compressed form. So instead of using ifstream I might want to implement my own input stream. At least that's how I would do it in Java. In Java I would write a custom class extending the <code>InputStream</code> class and implementing the <code>int read()</code> method. So that's pretty easy. And usage would look like this:</p>
  
  <pre><code>InputStream stream = new CompressedInputStream(new FileInputStream("somepic.imgz"));
  image.read(stream);
  </code></pre>
  
  <p>So using the same pattern maybe I want to do this in C++:</p>
  
  <pre><code>Image image;
  ifstream file("somepic.imgz");
  compressed_stream stream(file);
  stream &gt;&gt; image;
  </code></pre>
  
  <p>But maybe that's the wrong way, don't know. Extending the <code>istream</code> class looks pretty complicated and after some searching I found some hints about extending <code>streambuf</code> instead. But this <a href="http://icodesnip.com/snippet/cpp/an-example-of-implementing-a-custom-streambuf-performs-xor-encryption-dreamincode" rel="noreferrer">example</a> looks terribly complicated for such a simple task. </p>
  
  <p>So what's the best way to implement custom input/output streams (or streambufs?) in C++?</p>
  
  <h1>Solution</h1>
  
  <p>Some people suggested not using iostreams at all and to use iterators, boost or a custom IO interface instead. These may be valid alternatives but my question was about iostreams. The accepted answer resulted in the example code below. For easier reading there is no header/code separation and the whole std namespace is imported (I know that this is a bad thing in real code).</p>
  
  <p>This example is about reading and writing vertical-xor-encoded images. The format is pretty easy. Each byte represents two pixels (4 bits per pixel). Each line is xor'd with the previous line. This kind of encoding prepares the image for compression (usually results in lot of 0-bytes which are easier to compress).</p>
  
  <pre><code>#include &lt;cstring&gt;
  #include &lt;fstream&gt;
  
  using namespace std;
  
  /*** vxor_streambuf class ******************************************/
  
  class vxor_streambuf: public streambuf
  {
  public:
      vxor_streambuf(streambuf *buffer, const int width) :
          buffer(buffer),
          size(width / 2)
      {
          previous_line = new char[size];
          memset(previous_line, 0, size);
          current_line = new char[size];
          setg(0, 0, 0);
          setp(current_line, current_line + size);
      }
  
      virtual ~vxor_streambuf()
      {
          sync();
          delete[] previous_line;
          delete[] current_line;
      }
  
      virtual streambuf::int_type underflow()
      {
          // Read line from original buffer
          streamsize read = buffer-&gt;sgetn(current_line, size);
          if (!read) return traits_type::eof();
  
          // Do vertical XOR decoding
          for (int i = 0; i &lt; size; i += 1)
          {
              current_line[i] ^= previous_line[i];
              previous_line[i] = current_line[i];
          }
  
          setg(current_line, current_line, current_line + read);
          return traits_type::to_int_type(*gptr());
      }
  
      virtual streambuf::int_type overflow(streambuf::int_type value)
      {
          int write = pptr() - pbase();
          if (write)
          {
              // Do vertical XOR encoding
              for (int i = 0; i &lt; size; i += 1)
              {
                  char tmp = current_line[i];
                  current_line[i] ^= previous_line[i];
                  previous_line[i] = tmp;
              }
  
              // Write line to original buffer
              streamsize written = buffer-&gt;sputn(current_line, write);
              if (written != write) return traits_type::eof();
          }
  
          setp(current_line, current_line + size);
          if (!traits_type::eq_int_type(value, traits_type::eof())) sputc(value);
          return traits_type::not_eof(value);
      };
  
      virtual int sync()
      {
          streambuf::int_type result = this-&gt;overflow(traits_type::eof());
          buffer-&gt;pubsync();
          return traits_type::eq_int_type(result, traits_type::eof()) ? -1 : 0;
      }
  
  private:
      streambuf *buffer;
      int size;
      char *previous_line;
      char *current_line;
  };
  
  
  /*** vxor_istream class ********************************************/
  
  class vxor_istream: public istream
  {
  public:
      vxor_istream(istream &amp;stream, const int width) :
          istream(new vxor_streambuf(stream.rdbuf(), width)) {}
  
      virtual ~vxor_istream()
      {
          delete rdbuf();
      }
  };
  
  
  /*** vxor_ostream class ********************************************/
  
  class vxor_ostream: public ostream
  {
  public:
      vxor_ostream(ostream &amp;stream, const int width) :
          ostream(new vxor_streambuf(stream.rdbuf(), width)) {}
  
      virtual ~vxor_ostream()
      {
          delete rdbuf();
      }
  };
  
  
  /*** Test main method **********************************************/
  
  int main()
  {
      // Read data
      ifstream infile("test.img");
      vxor_istream in(infile, 288);
      char data[144 * 128];
      in.read(data, 144 * 128);
      infile.close();
  
      // Write data
      ofstream outfile("test2.img");
      vxor_ostream out(outfile, 288);
      out.write(data, 144 * 128);
      out.flush();
      outfile.close();
  
      return 0;
  }
  </code></pre>