I have to use a program written in C that read data from a binary file in this way
nCnt = 0;
for (i=0;i<h.nsph;++i) {
fread(&gp,sizeof(struct gas_particle),1,fp);
if (bGas) {
kd->p[nCnt].iOrder = nCnt;
for (j=0;j<3;++j) kd->p[nCnt].r[j] = gp.pos[j];
++nCnt;
}
}
The above code is not the whole code of the program I'm using but only the part relevant for my question. I need to read the positions of nCnt
particles, i.e. the coordinate for each particle.
I have these positions in a python array, which looks like this
pos=array([[[ 0.4786236 , 0.49046784, 0.48877147],
[ 0.47862025, 0.49042325, 0.48877267],
[ 0.47862737, 0.49039413, 0.4887735 ],
...,
[ 0.4785084 , 0.49032556, 0.48860968],
[ 0.47849332, 0.49041115, 0.48877266],
[ 0.47849161, 0.49041022, 0.48877176]]])
How should I write this array in a binary file so that the C code would read it fine?
Use the python module array
and it's tofile() method to write the data in a format which C can read or the IO routines if you use numpy.
With the number of digits, the 'f'
format (float) should work.
In C, you can read each line like so:
float values[3];
fread( values, sizeof( float ), 3, fh );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With