Search code examples
c++bmpfgetc

C++: Trouble reading .BMP files; end of file reached earlier than expected


i am currently trying to read .BMP files using C++, but somehow after reading a few bytes the end of the file is reached (fgetc() returns -1). I've reduced the problem to a minimal example:

#include <iostream>

int main()
{
    // Open file
    FILE* file = fopen("C:/Path/to/file", "r");

    // Get and print file size in bytes
    fseek(file, 0L, SEEK_END);
    std::cout << ftell(file) << std::endl;
    rewind(file);

    int byte, i = 0;
    do
    {
        // Get each byte
        byte = fgetc(file);
        // Print i and value of byte
        std::cout << i << ", " << byte << std::endl;
        i++;
    }
    // Stop reading when end of file is reached
    while (byte != EOF);

    std::cin.get();

    return 0;
}

When using this to read .BMP files (problem does not occur on simple formats like .txt files), It reads the file length correctly, but finds the EOF way before reaching the end of the file.

For example, using this file, it reads a file length of 120054, but fgetc() returns -1 at i=253.

What exactly am i doing wrong, and how can i fix this problem?


Solution

  • Change

    FILE* file = fopen("C:/Path/to/file", "r");
    

    to

    FILE* file = fopen("C:/Path/to/file", "rb");
    

    to read the file in binary mode. That usually helps to avoid such strange errors.