title: How to read N bytes from a file continuously untill the EOF
body: <p>I am trying a wave to base 64 converter program.</p>
  
  <p>I am trying this following code snippet: </p>
  
  <pre><code>    vector&lt;char&gt; in(3);
      std::string out = "abcd";         //four letter garbage value as initializer
      ifstream file_ptr(filename.c_str(), ios::in | ios::binary);
  
      unsigned int threebytes = 0;
      //Apply the Base 64 encoding algorithm
      do {
          threebytes = (unsigned int) file_ptr.rdbuf()-&gt;sgetn(&amp;in[0], 3);
          if (threebytes &gt; 0) {
              EncodeBlock(in, out, (int)threebytes);  //Apply conversion algorithm to convert 3 bytes into 4
              outbuff = outbuff + out;                //Append the 4 bytes got from above step to the output
          }
      } while (threebytes == in.size());
  
      file_ptr.close();
  </code></pre>
  
  <p>In encode block where the Base64 encoding algorithm is written</p>
  
  <pre><code>void EncodeBlock(const std::vector&lt;char&gt;&amp; in, std::string&amp; out, int len) {
      using namespace std;
      cb64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  
      out[0] = cb64[(int) (in[0] &gt;&gt; 2)];
      out[1] = cb64[(int) (((in[0] &lt;&lt; 6) &gt;&gt; 2) | (in[1] &gt;&gt; 4))];
      out[2] = (len &gt; 1) ?
               cb64[(int) (((in[1] &lt;&lt; 4) &gt;&gt; 2) | (in[2] &gt;&gt; 6))] :
               '=';
      out[3] = (len &gt; 2) ?
               cb64[(int) ((in[2] &lt;&lt; 2) &gt;&gt; 2)] :
               '=';
  
  }
  </code></pre>
  
  <p>The <code>cb64</code> is a 64 length long string but the index generated by bit manipulation sometimes fall out of range (0 to 63).</p>
  
  <p><strong><em>Why!!!</em></strong></p>