sven
sven

Reputation: 1121

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?

Upvotes: 1

Views: 1562

Answers (2)

Ingo Leonhardt
Ingo Leonhardt

Reputation: 9894

Each ^@ represents one binary 0x00, such as ^A represents 0x01, ^B represents 0x02 and so on. Take a look at the Hex dump you have posted. As sizeof( int ) is 4 on your platform, for each example_array[i].x you will find four bytes, followed by three more bytes that contain the string y. You will see, your first x is written as 00 00 00 00, your second x is 01 00 00 00 and that's exactly how integers are stored on your system. If you wanted to write the values as strings, e.g. to have a platform independent output file, you can use something like

fprintf( fp, "%d %s ", example_array[i].x, example_array[i].y )

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

^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.

Upvotes: 2

Related Questions