title: Writing/reading structure to/from binary file in c++
body: <p>I'm building a database tool and all I want to do is write a structure to a file in binary and then read it in again. The following is the closest I could find on the web for doing that, but it has major problems:</p>
  
  <pre><code>#include &lt;fstream&gt;
  #include &lt;iostream&gt;
  #include &lt;vector&gt;
  #include &lt;string.h&gt;
  
  using namespace std;
  
  
  typedef struct student
  {
      char name[10];
      int age;
      vector&lt;int&gt; grades;
  }student_t;
  
  int main()
  {
      student_t apprentice[3];  
      strcpy(apprentice[0].name, "john");
      apprentice[0].age = 21;
      apprentice[0].grades.push_back(1);
      apprentice[0].grades.push_back(3);
      apprentice[0].grades.push_back(5);    
  
      strcpy(apprentice[1].name, "jerry");
      apprentice[1].age = 22;
      apprentice[1].grades.push_back(2);
      apprentice[1].grades.push_back(4);
      apprentice[1].grades.push_back(6);
  
      strcpy(apprentice[2].name, "jimmy");
      apprentice[2].age = 23;
      apprentice[2].grades.push_back(8);
      apprentice[2].grades.push_back(9);
      apprentice[2].grades.push_back(10);
  
      // Serializing struct to student.data
      ofstream output_file("students.data", ios::binary);
      output_file.write((char*)&amp;apprentice, sizeof(apprentice));
      output_file.close();
  
      // Reading from it
      ifstream input_file("students.data", ios::binary);
      student_t master[3];
      input_file.read((char*)&amp;master, sizeof(master));   
  
      apprentice[0].grades[0]=100; // ALTERING THE INPUT STRUCTURE AFTER WRITE
  
      for (size_t idx = 0; idx &lt; 3; idx++)
      {
          // If you wanted to search for specific records, 
          // you should do it here! if (idx == 2) ...
  
          cout &lt;&lt; "Record #" &lt;&lt; idx &lt;&lt; endl;
          cout &lt;&lt; "Name: " &lt;&lt; master[idx].name &lt;&lt; endl;
          cout &lt;&lt; "Age: " &lt;&lt; master[idx].age &lt;&lt; endl;
          cout &lt;&lt; "Grades: " &lt;&lt; endl;
          for (size_t i = 0; i &lt; master[idx].grades.size(); i++)
             cout &lt;&lt; master[idx].grades[i] &lt;&lt; " ";
          cout &lt;&lt; endl &lt;&lt; endl;
      }
  
      return 0;
  }
  </code></pre>
  
  <p>This seems to write the file, read it back and then print to screen but unfortunately: Firstly the program crashes with a debug assertion fail (dbgdel.cpp line 52) when it tries to close, and secondly, altering the <em>input</em> structure after writing (as I have in the example) alters the supposedly read structure. I guess what is happening is that somehow "Data" and "inData" are the same thing (which would explain the crash as it would try to delete the same thing from memory twice). Can anyone get this working? I've tried everything I can think of.</p>