title: Storing vector of variable-size structs in a binary file in c++
body: <p>I am attempting to read and write a vector of structs into a file. Iterating through each struct, first I write the size of the following struct, then I write the structure. I encounter crashes when reading the file.</p>
  
  <p>Structure:</p>
  
  <pre><code>struct Book {
  
     string author;
     string title;
     string isbn;
     int copies;
     Status status;
  
  };
  </code></pre>
  
  <p>Loading from file:</p>
  
  <pre><code>void load_books(vector&lt;Book&gt; *books) {
  ifstream readFile;
  int read_size;
  Book temp;
  
  readFile.open(BOOK_DB_FILE.c_str(), ios::in | ios::binary) ;
  
  while(readFile.read(reinterpret_cast&lt;char*&gt; (&amp;read_size), sizeof(read_size))) {
      cout &lt;&lt; read_size &lt;&lt; endl;
  
      if (!readFile.read(reinterpret_cast&lt;char*&gt; (&amp;temp), read_size)) {
          cout &lt;&lt; "Failed to read library.dat!" &lt;&lt; endl;
      }
  
      cout &lt;&lt; "Attempting to load book..." &lt;&lt; endl;
      cout &lt;&lt; temp.title &lt;&lt; ":" &lt;&lt; temp.copies &lt;&lt; endl;
  
      (*books).push_back(temp);
  
  }
  cout &lt;&lt; "Loaded books!" &lt;&lt; endl;
  
  }
  </code></pre>
  
  <p>Writing to file:</p>
  
  <pre><code>void save_books(vector&lt;Book&gt; *books) {
  ofstream writeFile;
  int write_size;
  
  writeFile.open(BOOK_DB_FILE.c_str(), ios::out | ios::binary);
  
  for (int ind = 0 ; ind &lt; (*books).size(); ind++) {
      Book book = (*books)[ind];
      write_size = sizeof(book);
  
      cout &lt;&lt; "Writing book with size: " &lt;&lt; write_size &lt;&lt; endl;
      cout &lt;&lt; book.copies &lt;&lt; " of " &lt;&lt; book.title &lt;&lt; " by " &lt;&lt; book.author &lt;&lt; endl;
  
      writeFile.write(reinterpret_cast&lt;char*&gt;(&amp;write_size), sizeof(write_size));
      writeFile.write(reinterpret_cast&lt;char*&gt;(books + ind), write_size);
  }
  
  }
  </code></pre>