第一次调用fread后FTELL错误 [英] ftell error after the first call to fread
问题描述
所以我有一个非常简单的程序,读取一个文件的第3个字节:
So I have a very simple program that reads the 3 first bytes of a file:
int main(void)
{
FILE *fd = NULL;
int i;
unsigned char test = 0;
fd = fopen("test.bmp", "r");
printf("position: %ld\n", ftell(fd));
for (i=0; i<3; i++) {
fread(&test, sizeof (unsigned char), 1, fd);
printf("position: %ld char:%X\n", ftell(fd), test);
}
return (0);
}
当我用一个文本文件试试它工作得很好:
When I try it with a text file it works fine:
position: 0
position: 1 char: 61
position: 2 char: 62
position: 3 char: 63
但是当我用一个PNG运行它,例如我得到:
but when I run it with a PNG for example I get:
position: 0
position: 147 char:89
position: 148 char:50
position: 149 char:4E
请注意,该文件的第3个字节确实是89 50 4E,但我不知道那里的147来的。
随着bmp文件获得:
Note that the 3 first bytes of the file are indeed 89 50 4E but I don't know where the 147 comes from. With a bmp file I get:
position: 0
position: -1 char:42
position: 0 char:4D
position: 1 char:76
你知道这些第一位置从何而来?
非常感谢您的帮助。
Do you know where these first positions come from? Thanks a lot for your help
推荐答案
您需要以二进制方式打开文件:
You need to open the file in binary mode:
fd = fopen("test.bmp", "rb");
如果您尝试读取的二进制文件,如在文本模式下的位图,分别对应回车换行和字节混淆的东西。
If you try to read a binary file like a bitmap in text mode, the bytes corresponding to carriage returns and linefeeds confuse things.
这篇关于第一次调用fread后FTELL错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!