tags:

views:

158

answers:

4

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.

+3  A: 

You're reading successive 512-byte chunks from your file each time round the loop, and printing only one byte of each chunk. You might want to read those 512 bytes in one go, then print them afterwards, like this:

fread(&bytes, sizeof(bytes), 1, fp);
for(i = 0;i < 512;i++) {
    printf("bytes[%d]: %x\n", i, bytes[i]);
}

(Also: some error checking wouldn't go amiss, and as Dav points out, you should check that you really are reading the expected number of bytes from the file.)

RichieHindle
Might also want to check that the full 512 bytes were actually read (if the file is shorter than 512 byes, probably don't want to try to output anything beyond the actual length).
Amber
Ah excellent, now the data is a bit more as expected bytes[0]: 55 bytes[1]: ffffffaa bytes[2]: 55 bytes[3]: ffffffaa bytes[4]: 60 bytes[5]: 0 bytes[6]: 0 bytes[7]: 0 bytes[8]: 17 bytes[9]: a bytes[10]: 0 bytes[11]: 0Thank you much for the explanation.
mauvehead
@mauvehead: you should probably accept this answer ;-)
SamB
A: 

Couple of comments:

1) You have fread in a loop executing 512 times and you are reading 512 bytes each time. Move the fread out of the loop and read it in one go or change parameter 2 to fread to the sizeof int if you want to read it in the loop.

2) You are not checking the number of bytes actually read or if the files was successfully opened.

drewk
+3  A: 

RichieHindle has already solved the major part of the problem, now I'd like to help with the minor part.

When you're printing the results, your chars are being extended to ints. For a positive number this doesn't matter, but for a negative number (anything >= 0x80) you get a bunch of sign bits inserted at the beginning. It's easy to fix:

printf("bytes[%d]: %x\n", i, bytes[i] & 0xff); 
Mark Ransom
+1  A: 

Additional note. There is an off-by-one error in the loop, you are printing 513 elements.

Plow
+1: Good point!
RichieHindle