开发者

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

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.


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 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); 


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜