7

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?

4
  • Presumably that is a numpy array? Commented Mar 26, 2013 at 11:30
  • 1
    Have you checked this: stackoverflow.com/questions/807863/… (proposed solution uses docs.python.org/2/library/array.html)? Commented Mar 26, 2013 at 11:34
  • Don't you want to stringify your data for universality? For example you can store it in JSON, in that case you won't depend on endianness or bitness. Commented Mar 26, 2013 at 11:41
  • 2
    You should show the declaration of the struct gas_particle. Also, fread() (like all I/O) can fail, the return value should be checked. Commented Mar 26, 2013 at 12:08

1 Answer 1

6

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 );
Sign up to request clarification or add additional context in comments.

5 Comments

@unwind: What specifically isn't C?
It's better now, the strange declaration of values has been fixed. Still, it's missing an argument to fread() and the arguments that are present are given in the wrong order.
Why does the answer include any C at all though? The OP said he has to use a C program that was already written.
@JohnY: Ah, I somehow missed that.
Removed my downvote now that the fread() call at least would build. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.