Search code examples
clinuxbinaryfilesfwrite

writing int value to a binary file by fwrite


I have the below example C code to write int and char array to a file on Linux OS.

int main(void){
    struct eg{
        int x;
        char y[3];
    };

    struct eg example_array[5] = {{ 0, {0}}};

    int i;
    for(i=0;i<3;i++){
        example_array[i].x = i;
        strcpy(example_array[i].y,"12");
    }

    FILE *fp;
    fp = fopen("/home/ubuntu/example", "wb");
    fwrite(&example_array, sizeof(struct eg), 5, fp);
    fclose(fp);

return 0;
}

nano example shows the content as ^@^@^@^@12^@^@^A^@^@^@12^@^@^B^@^@^@12^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@

hexedit example shows it as

00000000   00 00 00 00  31 32 00 00  01 00 00 00  31 32 00 00  02 00 00 00  31 32 00 00  00 00 00 00  ....12......12......12......
0000001C   00 00 00 00  00 00 00 00  00 00 00 00                                                      ............

I don't see the example_array[i].x values on the binary file. Could anyone tell me how I should have used the fwrite on the above code?

and what do ^@^@^@^@^@ and ...... represent? are they blank spaces?


Solution

  • ^X encodes bytes with non-printable ASCII values. ^@ means 0, ^A means 1, ^B means 2, and so on.

       int   ch[] padding
    -------- ---- -------
    ^@^@^@^@ 12^@   ^@
    ^A^@^@^@ 12^@   ^@
    ^B^@^@^@ 12^@   ^@
    ^@^@^@^@ ^@^@   ^@
    ^@^@^@^@ ^@^@   ^@
    ^@^@
    

    Your computer stores the data starting with least significant byte. First four columns represent your int; the next three are the char[3]. Finally, there is a padding of 1 byte between the structs.