title: Write a table (of doubles) to binary file IO C++
body: <p>I need to write a matrix with four columns ("g_Grid.r", "g_Grid.t", "g_Grid.b", "g_Grid.ph")</p>
  
  <p>Normally, I write to file using file stream:</p>
  
  <pre><code>ofstream fout; 
  fout.open("GRID.dat");
   for (int m=0;m&lt;N_PH;++m)
      {   
      for (int k=0;k&lt;N_B;++k)
          {
            for (int j=0;j&lt;N_T;++j)
              {   
              for (int i=0;i&lt;N_R;++i)
                  {
                    fout &lt;&lt; setprecision(32) &lt;&lt; g_Grid.r[i]&lt;&lt;" "&lt;&lt;g_Grid.t[j]&lt;&lt;" "&lt;&lt;g_Grid.b[k]&lt;&lt;" "&lt;&lt;g_Grid.ph[m]&lt;&lt; endl;
  
                  }
              }
          }
      }
   fout.close();
  </code></pre>
  
  <p>It works fine, but now I'm dealing very large (long) matrix and it takes ages to write the formatted output (".txt"). Since I really do NOT need the file to be formatted, it prefer to write it as a binary file.</p>
  
  <p><strong>QUESTION:</strong> given four vectors/arrays (r,t,b,ph), how to write <strong>a table</strong> to binary file? (I use matlab to read this file later, and also need to read it as a binary table)</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Normally, I use the following simple code to write binary file:</p>
  
  <pre><code>ofstream myFile (fileName, ios::out | ios::binary);
  double val;
  for (int m=0;m&lt;N_PH;++m)
      {   
      for (int k=0;k&lt;N_B;++k)
          {
            for (int j=0;j&lt;N_T;++j)
              {   
              for (int i=0;i&lt;N_R;++i)
                  {
                    val = g_N.Amp[m][k][j][i];
                    myFile.write(reinterpret_cast&lt;const char*&gt;(&amp;val), sizeof(val));
                  }
              }
          }
      }
  myFile.close();
  </code></pre>
  
  <p>But this one will yield only "one-column" while it will be read by matlab later.</p>