title: C++ writing and reading doubles from a binary file
body: <p>I want to perform disk I/O operations for a program that takes too much RAM. 
  I use matrices of doubles and think writing them to disk as bytes is the fastest way (I need to preserve the double precision).</p>
  
  <p>How to do it with portability?</p>
  
  <p>I found this code (<a href="http://www.daniweb.com/software-development/cpp/threads/68214" rel="nofollow">here</a>) but the author says it's not portable...</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;fstream&gt;
  
  int main()
  {
      using namespace std;
  
      ofstream ofs( "atest.txt", ios::binary );
  
      if ( ofs ) {
          double pi = 3.14;
  
          ofs.write( reinterpret_cast&lt;char*&gt;( &amp;pi ), sizeof pi );
          // Close the file to unlock it
          ofs.close();
  
          // Use a new object so we don't have to worry
          // about error states in the old object
          ifstream ifs( "atest.txt", ios::binary );
          double read;
  
          if ( ifs ) {
              ifs.read( reinterpret_cast&lt;char*&gt;( &amp;read ), sizeof read );
              cout &lt;&lt; read &lt;&lt; '\n';
          }
      }
  
      return 0;
  }
  </code></pre>