title: Reading binary files in C++
body: <p>I am trying to write a program that reads in binary files using C++. I am running into some unusual output that I was hoping for some help with.</p>
  
  <p>I have a binary file that starts with these 4 bytes:</p>
  
  <p>A1 B2 C3 D4 (verified using <code>hexdump -C</code>)</p>
  
  <p>And here is the code I am using to read these 4 bytes in:</p>
  
  <pre><code>#include &lt;iostream&gt; // for reading and writing files
  #include &lt;fstream&gt;
  
  using namespace std;
  
  char * buffer;
  unsigned int LENGTH = 4;
  
  int main(int argc, char ** argv)
  {
      // open the binary file
      ifstream infile ("dump", ios::binary | ios::in);
  
      // create a buffer
      buffer = new char[LENGTH];
  
      // read LENGTH bytes from the file
      infile.read(buffer, LENGTH);
  
      // append the null byte to terminate the string
      buffer[LENGTH] = '\0';
  
      // loop over the 4 bytes read, and print
      for(int i = 0; i &lt; LENGTH; i++)
      {
         printf("Buffer[%d] is %X\n", i, buffer[i]);
      }
  
      delete[] buffer;
      infile.close();
  
  
      return 0;
  }
  </code></pre>
  
  <p>This program gives me these actual results: </p>
  
  <pre><code>Buffer[0] is FFFFFFA1
  Buffer[1] is FFFFFFB2
  Buffer[2] is FFFFFFC3
  Buffer[3] is FFFFFFD4
  </code></pre>
  
  <p>BUT, I would expect these results: </p>
  
  <pre><code>Buffer[0] is A1
  Buffer[1] is B2
  Buffer[2] is C3
  Buffer[3] is D4
  </code></pre>
  
  <p>Can anyone explain to me where the 3 0xFF bytes are coming from ? It only seems to be affecting the first 4 bytes of the file, the next 4 bytes print out as expected without any 0xFF bytes prepended.</p>