我目前正在尝试使用 C++ 读取 .BMP 文件,但不知何故在读取几个字节后到达文件末尾(fgetc()返回-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;
}
Run Code Online (Sandbox Code Playgroud)
当使用它读取.BMP文件时(在.txt文件等简单格式上不会出现问题),它正确读取文件长度,但在到达文件末尾之前找到EOF方式。
例如,使用此 file,它读取文件长度为 120054,但在 i=253 时fgetc()返回。-1
我到底做错了什么,我该如何解决这个问题?
在 DOS/Windows 上以纯“r”模式读取文件可能会将 ASCII 26 (^Z) 视为“文件结尾”。它还可能将行结尾从 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
Run Code Online (Sandbox Code Playgroud)
该位置是八进制的375,十进制的253。听起来有点熟?:)
使用“rb”:
FILE* file = fopen("C:/Path/to/file", "rb");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
325 次 |
| 最近记录: |