title: C++ Storing objects in a file
body: <p>I have a list of objects that I would like to store in a file as small as possible for later retrieval. I have been carefully reading <a href="http://www.daniweb.com/forums/thread6542.html#" rel="nofollow noreferrer">this tutorial</a>, and am beginning (I think) to understand, but have several questions. Here is the snippet I am working with:</p>
  
  <pre><code>    static bool writeHistory(string fileName)
  {
      fstream historyFile;
      historyFile.open(fileName.c_str(), ios::binary);
      if (historyFile.good())
      {
          list&lt;Referral&gt;::iterator i;
          for(i = AllReferrals.begin(); 
                  i != AllReferrals.end();
                  i++)
          {
              historyFile.write((char*)&amp;(*i),sizeof(Referral));
          }
          return true;
      } else return false;
  }
  </code></pre>
  
  <p>Now, this is adapted from the snippet</p>
  
  <pre><code>file.write((char*)&amp;object,sizeof(className));
  </code></pre>
  
  <p>taken from the tutorial. Now what I believe it is doing is converting the object to a pointer, taking the value and size and writing that to the file. But if it is doing this, why bother doing the conversions at all? Why not take the value from the beginning? And why does it need the size? Furthermore, from my understanding then, why does</p>
  
  <pre><code>historyFile.write((char*)i,sizeof(Referral));
  </code></pre>
  
  <p>not compile? i is an iterator (and isn't an iterator a pointer?). or simply </p>
  
  <pre><code>historyFile.write(i,sizeof(Referral));
  </code></pre>
  
  <p>Why do i need to be messing around with addresses anyway? Aren't I storing the data in the file? If the addresses/values are persisting on their own, why can't i just store the addresses deliminated in plain text and than take their values later?</p>
  
  <p>And should I still be using the .txt extension? <strong>&lt; edit></strong> what should I use instead then? I tried .dtb and was not able to create the file. <strong>&lt; /edit></strong> I actually can't even seem to get file to open without errors with the ios::binary flag. I'm also having trouble passing the filename (as a string class string, converted back by c_str(), it compiles but gives an error).</p>
  
  <p>Sorry for so many little questions, but it all basically sums up to <strong>how to efficiently store objects in a file?</strong></p>