第一次调用fread后出现ftell错误

时间:2010-07-09 09:51:46

标签: c fread ftell

所以我有一个非常简单的程序,它读取文件的3个第一个字节:

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

当我尝试使用文本文件时,它可以正常工作:

position: 0
position: 1 char: 61
position: 2 char: 62
position: 3 char: 63

但是当我用PNG运行时,我得到:

position: 0
position: 147 char:89
position: 148 char:50
position: 149 char:4E

请注意,文件的3个第一个字节确实是89 50 4E,但我不知道147来自哪里。 使用bmp文件我得到:

position: 0
position: -1 char:42
position: 0 char:4D
position: 1 char:76

你知道这些第一个职位来自哪里吗? 非常感谢您的帮助

2 个答案:

答案 0 :(得分:3)

您需要以二进制模式打开文件:

fd = fopen("test.bmp", "rb");

如果您尝试在文本模式下读取二进制文件(如位图),则回车和换行符对应的字节会使事情混淆。

答案 1 :(得分:0)

请查看此问题Reading bytes from bmp file

看起来问题处于打开它的模式。