title: Having trouble serializing binary data using ifstream and ofstream
body: <p>I am trying to serialize a Plain Old Datastructure using ifstream and ofstream and I wasn't able to get it to work. I then tried to reduce my problem to an ultra basic serialization of just a char and int and even that didn't work. Clearly I'm missing something at a core fundamental level.</p>
  
  <p>For a basic structure:</p>
  
  <pre><code>struct SerializeTestStruct
  {
      char mCharVal;
      unsigned int mIntVal;
  
      void Serialize(std::ofstream&amp; ofs);
  };
  </code></pre>
  
  <p>With serialize function:</p>
  
  <pre><code>void SerializeTestStruct::Serialize(std::ofstream&amp; ofs)
  {
      bool isError = (false == ofs.good());
      if (false == isError)
      {
          ofs.write((char*)&amp;mCharVal, sizeof(mCharVal));
          ofs.write((char*)&amp;mIntVal, sizeof(mIntVal));
      }
  }
  </code></pre>
  
  <p>Why would this fail with the following short program?</p>
  
  <pre><code>//ultra basic serialization test.
      SerializeTestStruct* testStruct = new SerializeTestStruct();
      testStruct-&gt;mCharVal = 'y';
      testStruct-&gt;mIntVal = 9;
  
      //write
      std::string testFileName = "test.bin";
      std::ofstream fileOut(testFileName.data());
      fileOut.open(testFileName.data(), std::ofstream::binary|std::ofstream::out);
      fileOut.clear();
      testStruct-&gt;Serialize(fileOut);
  
      fileOut.flush();
      fileOut.close();
  
      delete testStruct;
  
      //read
      char * memblock;
      std::ifstream fileIn (testFileName.data(), std::ifstream::in|std::ifstream::binary);
      if (fileIn.is_open())
      {
          // get length of file:
          fileIn.seekg (0, std::ifstream::end);
          int length = fileIn.tellg();
          fileIn.seekg (0, std::ifstream::beg);
  
          // allocate memory:
          memblock = new char [length];
          fileIn.read(memblock, length);
          fileIn.close();
  
          // read data as a block:
          SerializeTestStruct* testStruct2 = new(memblock) SerializeTestStruct();
  
          delete[] testStruct2;
      }
  </code></pre>
  
  <p>When I run through the code I notice that <code>memblock</code> has a "y" at the top so maybe it is working and it's just a problem with the <code>placement new</code> at the very end? After that placement new I end up with a <code>SerializeTestStruct</code> with values: 0, 0.</p>