问题
I need to write a matrix with four columns ("g_Grid.r", "g_Grid.t", "g_Grid.b", "g_Grid.ph")
Normally, I write to file using file stream:
ofstream fout;
fout.open("GRID.dat");
for (int m=0;m<N_PH;++m)
{
for (int k=0;k<N_B;++k)
{
for (int j=0;j<N_T;++j)
{
for (int i=0;i<N_R;++i)
{
fout << setprecision(32) << g_Grid.r[i]<<" "<<g_Grid.t[j]<<" "<<g_Grid.b[k]<<" "<<g_Grid.ph[m]<< endl;
}
}
}
}
fout.close();
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.
QUESTION: given four vectors/arrays (r,t,b,ph), how to write a table to binary file? (I use matlab to read this file later, and also need to read it as a binary table)
EDIT
Normally, I use the following simple code to write binary file:
ofstream myFile (fileName, ios::out | ios::binary);
double val;
for (int m=0;m<N_PH;++m)
{
for (int k=0;k<N_B;++k)
{
for (int j=0;j<N_T;++j)
{
for (int i=0;i<N_R;++i)
{
val = g_N.Amp[m][k][j][i];
myFile.write(reinterpret_cast<const char*>(&val), sizeof(val));
}
}
}
}
myFile.close();
But this one will yield only "one-column" while it will be read by matlab later.
回答1:
To write binary data into a file, you first need to open the file in binary mode, you need to use fstream::write
. It takes a char *
argument, and writes a number of bytes from that - the char *
argument requires a cast if the data is not an array of char
or pointer to char
.
So as to avoid having several calls to write, it's better to stuff the data into a structure.
So, the following should do what you need:
ofstream fout;
fout.open("GRID.dat", ios::binary);
for (int m=0;m<N_PH;++m)
{
for (int k=0;k<N_B;++k)
{
for (int j=0;j<N_T;++j)
{
for (int i=0;i<N_R;++i)
{
struct X
{
double a, b, c, d;
} x;
x.a = g_Grid.r[i];
x.b = g_Grid.t[j];
x.c = g_Grid.b[k];
x.d = g_Grid.ph[m];
fout.write(reinterpret_cast<char *>(&x), sizeof(x));
}
}
}
}
fout.close();
来源:https://stackoverflow.com/questions/17061122/write-a-table-of-doubles-to-binary-file-io-c