C++:无法读取 .BMP 文件;比预期更早到达文件末尾

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

我目前正在尝试使用 C++ 读取 .BMP 文件,但不知何故在读取几个字节后到达文件末尾 (fgetc() returns -1)。我已将问题简化为一个最小的例子:

#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;
}

当使用它读取.BMP文件时(问题不会发生在像.txt文件这样的简单格式上),它正确读取文件长度,但在到达文件末尾之前找到EOF方式。

比如使用this file,读取的文件长度为120054,但是fgetc() returns -1 at i=253.

我究竟做错了什么,我该如何解决这个问题?

改变

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

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

以二进制模式读取文件。这通常有助于避免此类奇怪的错误。

在 DOS/Windows 上以纯 "r" 模式读取文件可能会将 ASCII 26 (^Z) 视为 "end of file"。它还可能将行结尾从 CR LF (13 10) 转换为 LF (10),这也是您不想要的。

查看您的样本文件,我确实看到了那个字符(它是十六进制的 1A):

0000340 0c 1f 15 0e 1f 15 0e 1f 14 10 1f 14 10 21 17 10
0000360 21 17 10 22 18 11 23 19 12 25 19 13 26[1a]14 26

位置为八进制375,十进制为253。听起来有点熟? :)

使用"rb":

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