简体   繁体   中英

Read binary file in C

I have file test.bin which has content: 33 0F 13 05 54 65 73 74 20 13 06 55 73 65 72 20 31 When I read this file I get such result: 3333203046203133203035203534203635. I can't understand what I do in a wrong way.

void ReadBinFile()
{
    int i;
    FILE *ptr;
    unsigned char buffer2[17];
    ptr = fopen("test.bin","r");
    fread(buffer2,sizeof(buffer2),1,ptr);

    for(i = 0; i<17; i++)
        printf("%x", buffer2[i]);
}

You are getting the correct answer. You have written the file "33 0F 13 05 54 65 73 74 20 13 06 55 73 65 72 20 31" And you are getting the reply "3333203046203133203035203534203635" which happens to be the ASCII, in hex, of the data you wrote.

You need to write the data to a binary file as binary and that will fix your issue.

**EDIT because tis just too big for a comment **

When you want to work with binary files you need to open the files as binary, write to the files as binary, read from the files as binary, etc. fprintf() doesn't work on binary files. So to make you code work you need to make these changes: (This is a quick hack of your code, it needs a lot of polishing)

void WriteBinFile(void)
{
    FILE *ptr; 
    unsigned char a[] = {0xFF}; 
    ptr = fopen("test.bin","wb"); 
    fwrite (a, sizeof(unsigned char), 1, ptr);
    fclose (ptr);
}

void ReadBinFile(void)
{
    static const size_t BufferSize = 17;
    int i;
    FILE *ptr;
    unsigned char buffer2[BufferSize];

    ptr = fopen("test.bin","rb");
    const size_t fileSize = fread(buffer2, sizeof(unsigned char), BufferSize, ptr);

    printf("File size = %d bytes\n", fileSize);
    printf("Size of each item in bytes = %d\n", sizeof(unsigned char));

    for(i = 0; i < (fileSize / sizeof(unsigned char)); i++)
    {
        printf("0x%x ", (int)buffer2[i]);
    }
    fclose (ptr);
}

int main (void)
{
    WriteBinFile();
    ReadBinFile();
    printf("\nPress enter to exit\n");
    return fgetc(stdin);
}

The Write function uses fwrite() to write characters to the file from the array of data (with one element in), it then closes the file. The read function does the same as before, but I have added some diagnostics so you can check the file and character size. It also only displays the data it has read, not the initialised memory in the buffer.

Also you MUST close files, otherwise you can't reopen them until your program exits.

Any problems, just shout.

It seem that you are reading the file as string and not as HEX. For example: "3" as string is 0x33 and " " as string is 0x20. So what "33 " is 0x333320 (the beginning of your example). This explain the missread. I hope it help :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM