fwrite in binary mode of ints not writing proper number of bytes

0

I am not able to understand the fread fwrite behavior of the following code snippet, exemplified by the code is straightforward:

#include <stdio.h>
int main(void)
{
    FILE *fp;
    int   arr[10] = {1,2,3,4,5,6,7,8,9,10};
    int   temp[100] = {0};
    int   i;

    fp = fopen("testdata.bin","wb");
    if( fp!= NULL ) {
        fwrite( arr,sizeof(int), 10, fp);
        fclose(fp);
    }
    fp = fopen("testdata.bin","rb");
    if( fp!= NULL ) {
        fread( temp,sizeof(int), 10, fp);
        fclose(fp);
    }
    for(i=0;i<100;i++)
        printf("%#x,",temp[i]);
    printf("\b \n");
    return 0;
}

The output on stdout is:

0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9,0xa,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

which makes sense. However, when I open the testdata.bin file, I see only two bytes for value (int) where I expect 4 bytes as size of int is 4 on my machine.

Here is the content of testdata.bin:

0x00000001: 01 00 02 00 03 00 04 00 05 00 06 00 07 00 08 00
0x00000010: 09 00 0a 00 

I would have expected

0x00000001: 01 00 00 00 02 00 00 00 03 00 00 00 ...

Any ideas?

c
asked on Stack Overflow Aug 17, 2017 by Vikas Yadav • edited Aug 17, 2017 by xaxxon

1 Answer

1

I think fwrite is working fine. Change the declaration of temp so the type is an array of one-byte unsigned characters:

unsigned char temp [100] = {0} ;

The current version of the code displays a four-byte integer each time in the print statement. This will confirm that the contents of the file are as you expect. On my machine:

0x1,0,0,0,0x2,0,0,0,0x3,0,0,0,0x4,0,0,0,0x5,0,0,0,0x6,0,0,0,0x7,0,0,0,0x8,0,0,0,0x9,0,0,0,0xa,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
answered on Stack Overflow Aug 17, 2017 by Patrick Kelly • edited Aug 17, 2017 by Patrick Kelly

User contributions licensed under CC BY-SA 3.0