ftell error after the first call to fread

蹲街弑〆低调 提交于 2019-12-20 04:12:31

问题


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

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

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


回答1:


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.




回答2:


Please look at this question Reading bytes from bmp file.

Looks like problem is in the mode of opening it.



来源:https://stackoverflow.com/questions/3211517/ftell-error-after-the-first-call-to-fread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!