Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing binary files in python to be read by C

Tags:

python

c

binary

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?

like image 514
Brian Avatar asked Mar 26 '13 11:03

Brian


1 Answers

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 );
like image 192
Aaron Digulla Avatar answered Nov 01 '22 06:11

Aaron Digulla