title: Reading and writing integers from/to a binary file in C++
body: <p>The trying to write a simple program that would write integers value into a file, then read and display the integers in the order it was written. The integers written into the file are {0,2,....18}. The following is the code:</p>
  
  <pre><code>// Example program
  #include &lt;iostream&gt;
  #include &lt;string&gt;
  #include &lt;sstream&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;fstream&gt;
  using namespace std;
  
  int main()
  {
      typedef unsigned int uint32_t;
      // Write to file
      std::ofstream osObj;
      string filename = "testFile";
      osObj.open(filename.c_str(), std::ofstream::binary);
  
      for (uint32_t i=0; i&lt;10; ++i)
      {
          uint32_t a = i*2;
          osObj.write(reinterpret_cast&lt;const char *&gt;(&amp;a), sizeof(a));
          //osObj.write((char *)(&amp;a), sizeof(a));
      }
  
      //read from file
      std::ifstream isObj;
      isObj.open(filename.c_str(), std::ofstream::binary);
      if (isObj.fail()) { cout&lt;&lt;"Failed to open file"&lt;&lt;endl; }
  
      for (uint32_t i=0; i&lt;10; ++i)
      {
          char val[sizeof(uint32_t)];
          isObj.read(val, sizeof(val));
          uint32_t* valUint = reinterpret_cast&lt;uint32_t *&gt;(val);
          cout&lt;&lt;*(valUint)&lt;&lt;endl;
      }
      return 0;
  }
  </code></pre>
  
  <p>This doesn't produce the expected result. I'm getting the following output:</p>
  
  <pre><code>62586880
  62586880
  62586880
  62586880
  62586880
  62586880
  62586880
  62586880
  62586880
  62586880
  </code></pre>
  
  <p>The byte ordering is little-endian. What am I missing? </p>