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!
I'm guessing you're on Windows; a byte with value (See the comments; this explanation is wrong, but the solution worked, presumably because there is a 0x1b
means "end of file" for a text file on Windows.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