reading struct in python from created struct in c

后端 未结 4 1091
广开言路
广开言路 2020-12-01 12:48

I am very new at using Python and very rusty with C, so I apologize in advance for how dumb and/or lost I sound.

I have function in C that creates a .dat file contai

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 13:33

    Some C code:

    #include 
    typedef struct { double v; int t; char c;} save_type;
    int main() {
        save_type s = { 12.1f, 17, 's'};
        FILE *f = fopen("output", "w");
        fwrite(&s, sizeof(save_type), 1, f);
        fwrite(&s, sizeof(save_type), 1, f);
        fwrite(&s, sizeof(save_type), 1, f);
        fclose(f);
        return 0;
    }
    

    Some Python code:

    import struct
    with open('output', 'rb') as f:
        chunk = f.read(16)
        while chunk != "":
            print len(chunk)
            print struct.unpack('dicccc', chunk)
            chunk = f.read(16)
    

    Output:

    (12.100000381469727, 17, 's', '\x00', '\x00', '\x00')
    (12.100000381469727, 17, 's', '\x00', '\x00', '\x00')
    (12.100000381469727, 17, 's', '\x00', '\x00', '\x00')
    

    but there is also the padding issue. The padded size of save_type is 16, so we read 3 more characters and ignore them.

提交回复
热议问题