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();