title: C++ fwrite and fread for string
body: <p>here's the piece of code that writes a string in a binary file:</p>
  
  <pre><code>std::string s("Hello");
  unsigned int N(s.size());
  fwrite(&amp;N,sizeof(N), 1 ,bfile);
  fwrite(s.c_str(),1, N ,bfile);
  fflush(bfile);
  </code></pre>
  
  <p>the piece to read the string:</p>
  
  <pre><code>std::string new_s("");
  unsigned int N(0);
  fread(&amp;N,sizeof(N),1,bfile);
  char* c(new char[N+1]);
  fread(c,1,N,bfile);
  c[N] = '\0';
  new_s = c;
  delete[] c;
  </code></pre>
  
  <p>Questions :</p>
  
  <ul>
  <li>is there a simpler way to do that ?</li>
  <li>when I write/read the file, should i take into account the null character <code>'\0'</code> that comes from the <code>c_str()</code> ?</li>
  </ul>
  
  <p>I have a side question which is related to <code>char* c(new char[N])</code> :</p>
  
  <ul>
  <li>i know that c++ doesn't allow to create a static array with for instance int <code>a[size_of_array]</code>, so the solution is to use a pointer created with <code>new[]</code> and deleted with <code>delete[]</code>. is this the only solution (if i can't use a <code>std::vector &lt; int &gt;</code> ), and would this solution be efficient ?</li>
  </ul>