Writing binary files in python to read C

I need to use a program written in C that reads data from a binary file 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 all the code of the program I use, but only the part related to my question. I need to read the positions of the nCnt particles, i.e. The coordinates for each particle. I have these positions in a python array that 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 do I write this array in a binary so that the C code reads it normally?

+6
source share
1 answer

Use the python array module and the tofile () method to write data in a format that C can read, or I / O Procedures if you use numpy .

With the number of digits, the format 'f' (float) should work.

In C, you can read each line as follows:

 float values[3]; fread( values, sizeof( float ), 3, fh ); 
+5
source

All Articles