feof() and fscanf() stop working after scanning byte 1b as a char. Is it because it is 'ESC' in ascii? What can I do?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-04 06:38:25

问题


I'm currently writing a program that processes PPM files (P6 type, not P3) The problem is that some images have the byte 0x1b which, according to the ascii table is known as 'ESC'

The following is pretty much my code:

// all the includes there, , , ...

int main(void)
{
    FILE *finput;
    int number[7];
    char r, g, b;

    finput = fopen("my.ppm", "r");

    /*
       The code where I read the P6 numRows numColumns 255\n

       ...Lets assume that part works well 
    */


    while(!feof(finput))
    {
       num[0] = fscanf(finput, "%c", &r);    // the "num[] = " part is for debugging
       num[1] = fscanf(finput, "%c", &g);    
       num[2] = fscanf(finput, "%c", &b);


       printf("%d\n", num[0]);
       printf("%d\n", num[1]);
       printf("%d\n", num[2]);



    }
return 0; //or whatever...
}

For some reason, fscanf starts returning -1 after reading the 'ESC' byte (but the one that reads it does not return -1)

So the sample output would be:

1 -1 -1


On the other hand, I read the "while(!feof()) is always wrong" and the one about big files with fscanf, but my ppm images are not bigger than 500x500 pixels...

What can/should I do in order to be able to keep reading?

Thank you for your help!


回答1:


I'm guessing you're on Windows; a byte with value 0x1b means "end of file" for a text file on Windows. (See the comments; this explanation is wrong, but the solution worked, presumably because there is a 0x1a in the data).

You should open the file in binary mode:

fopen("my.ppm", "rb");

That will read all the bytes successfully. (It will also read both the \r and the \n of end-of-line markers.)



来源:https://stackoverflow.com/questions/23433589/feof-and-fscanf-stop-working-after-scanning-byte-1b-as-a-char-is-it-because

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