Search code examples
c++cfwriteshort

Fwrite wrong answer


in my project I've write a.bin file which has sensor data in the form of unsigned short(16 bit LE values). but I've get wrong value. Can you guys suggest what is going wrong here?

#include<stdio.h>
int main()
{
    FILE *fp = fopen("a.bin","ab");
    unsigned short us;
    us=123;
    fwrite(&us,2,1,fp);
    printf("%04X",us); // 0x:007B
    us=1234;
    fwrite(&us,2,1,fp);
    printf("%04X",us); // 0x04D2
    us=-3145;
    fwrite(&us,2,1,fp);
    printf("%04X",us); // 0xF3B7
    fclose(fp);
}

After I do the fwrite()

a.bin
7b 00 d0 bc 04 d0 b8 d0 b7

But I want

a.bin
7b 00 04 d2 f3 b7

Solution

  • After fixing your errors, the code works for me just fine.

    Note that opening the file in mode "a" means "append". I changed it to "w", which will overwrite the existing file:

    fwrite.c:

    #include<stdio.h>
    int main(void)
    {
        FILE *fp = fopen("a.bin","wb");
        unsigned short us;
    
        us = 123;
        fwrite(&us, sizeof(us), 1, fp);
        printf("%04hX\n",us); // 007B
    
        us = 1234;
        fwrite(&us, sizeof(us), 1, fp);
        printf("%04hX\n",us); // 04D2
    
        us = -3145;
        fwrite(&us, sizeof(us), 1, fp);
        printf("%04hX\n",us); // F3B7
    
        fclose(fp);        
    
        return 0;
    }
    

    Result:

    $ gcc -Wall -Werror fwrite.c 
    $ ./a.out 
    007B
    04D2
    F3B7
    $ hexdump -Cv a.bin 
    00000000  7b 00 d2 04 b7 f3                                 |{.....|
    00000006