title: Reading binary istream byte by byte
body: <p>I was attempting to read a binary file byte by byte using an ifstream.  I've used istream methods like get() before to read entire chunks of a binary file at once without a problem.  But my current task lends itself to going byte by byte and relying on the buffering in the io-system to make it efficient.  The problem is that I seemed to reach the end of the file several bytes sooner than I should.  So I wrote the following test program:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;fstream&gt;
  
  int main() {
      typedef unsigned char uint8;
      std::ifstream source("test.dat", std::ios_base::binary);
      while (source) {
          std::ios::pos_type before = source.tellg();
          uint8 x;
          source &gt;&gt; x;
          std::ios::pos_type after = source.tellg();
          std::cout &lt;&lt; before &lt;&lt; ' ' &lt;&lt; static_cast&lt;int&gt;(x) &lt;&lt; ' '
                    &lt;&lt; after &lt;&lt; std::endl;
      }
      return 0;
  }
  </code></pre>
  
  <p>This dumps the contents of test.dat, one byte per line, showing the file position before and after.</p>
  
  <p>Sure enough, if my file happens to have the two-byte sequence 0x0D-0x0A (which corresponds to carriage return and line feed), those bytes are skipped.</p>
  
  <ul>
  <li>I've opened the stream in binary mode.  Shouldn't that prevent it from interpreting line separators?</li>
  <li>Do extraction operators always use text mode?</li>
  <li>What's the right way to read byte by byte from a binary istream?</li>
  </ul>
  
  <p>MSVC++ 2008 on Windows.</p>