Why am I not getting the expected results with fread() in C?

Posted by mauvehead on Stack Overflow See other posts from Stack Overflow or by mauvehead
Published on 2010-04-05T22:29:12Z Indexed on 2010/04/05 22:33 UTC
Read the original article Hit count: 298

Filed under:
|
|
|

Here is my code:

#include <stdio.h>

int main(void) {

        FILE *fp;
        unsigned int i;
        char bytes[512];
        fp = fopen("myFile","r");
        for(i = 0;i <= 512;i++) {
                fread(&bytes, sizeof(bytes), 1, fp);
                printf("bytes[%d]: %x\n", i, bytes[i]);
        }
}

Here is the expected output

$ hexdump myFile
0000000 aa55 aa55 0060 0000 0a17 0000 b1a5 a2ea
0000010 0000 0000 614c 7563 616e 0000 0000 0000
0000020 0000 0000 0a68 0000 1001 421e 0000 0000
0000030 f6a0 487d ffff ffff 0040 0000 002f 0000

But here is what I see from my program

bytes[0]: 55
bytes[1]: 8
bytes[2]: ffffffc8
bytes[3]: ffffffdd
bytes[4]: 22
bytes[5]: ffffffc8
bytes[6]: ffffff91
bytes[7]: 63
bytes[8]: ffffff82

My obvious guess is that I'm either addressing something incorrectly and receiving the wrong data back or I am printing it incorrectly and viewing it the wrong way.

© Stack Overflow or respective owner

Related posts about c

    Related posts about fread