Search code examples
cfile-iostdiomsvcrtfread

fread Only first 5 bytes of .PNG file


I've made a simple resource packer for packing the resources for my game into one file. Everything was going fine until I began writing the unpacker. I noticed the .txt file - 26 bytes - that I had packed, came out of the resource file fine, without anyway issues, all data preserved. However when reading the .PNG file I had packed in the resource file, the first 5 bytes were intact while the rest was completely nullified.

I traced this down to the packing process, and I noticed that fread is only reading the first 5 bytes of the .PNG file and I can't for the life of me figure out why. It even triggers 'EOF' indicating that the file is only 5 bytes long, when in fact it is a 787 byte PNG of a small polygon, 100px by 100px.

I even tested this problem by making a separate application to simply read this PNG file into a buffer, I get the same results and only 5-bytes are read.

Here is the code of that small separate application:

#include <cstdio>

int main(int argc, char** argv)
{
    char buffer[1024] = { 0 };
    FILE* f = fopen("test.png", "r");
    fread(buffer, 1, sizeof(buffer), f);
    fclose(f);        //<- I use a breakpoint here to verify the buffer contents
    return 0;
}

Can somebody please point out my stupid mistake?


Solution

  • Can somebody please point out my stupid mistake?

    Windows platform, I guess?

    Use this:

    FILE* f = fopen("test.png", "rb");
    

    instead of this:

    FILE* f = fopen("test.png", "r");
    

    See msdn for explanation.