title: How do I read an entire file into a std::string in C++?
body: <p>How do I read a file into a <code>std::string</code>, i.e., read the whole file at once?</p>
  
  <p>Text or binary mode should be specified by the caller. The solution should be standard-compliant, portable and efficient. It should not needlessly copy the string's data, and it should avoid reallocations of memory while reading the string.</p>
  
  <p>One way to do this would be to stat the filesize, resize the <code>std::string</code> and <code>fread()</code> into the <code>std::string</code>'s <code>const_cast&lt;char*&gt;()</code>'ed <code>data()</code>. This requires the <code>std::string</code>'s data to be contiguous which is not required by the standard, but it appears to be the case for all known implementations. What is worse, if the file is read in text mode, the <code>std::string</code>'s size may not equal the file's size.</p>
  
  <p>A fully correct, standard-compliant and portable solutions could be constructed using <code>std::ifstream</code>'s <code>rdbuf()</code> into a <code>std::ostringstream</code> and from there into a <code>std::string</code>. However, this could copy the string data and/or needlessly reallocate memory. </p>
  
  <ul>
  <li>Are all relevant standard library implementations smart enough to avoid all unnecessary overhead? </li>
  <li>Is there another way to do it? </li>
  <li>Did I miss some hidden Boost function that already provides the desired functionality?</li>
  </ul>
  
  <p><br></p>
  
  <pre><code>void slurp(std::string&amp; data, bool is_binary)
  </code></pre>