feof()和fscanf()在将字节1b扫描为char后停止工作。 是因为它在ascii中是’ESC’吗? 我能做什么?

我正在编写一个处理PPM文件的程序(P6类型,而不是P3)问题是一些图像的字节为0x1b,根据ascii表称为’ESC’

以下几乎是我的代码:

//所有包括那里,,, …

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... } 

由于某种原因,fscanf在读取’ESC’字节后开始返回-1(但是读取它的那个不返回-1)

所以样本输出将是:

1 -1 -1


另一方面,我读到“while(!feof())总是错误的”和关于fscanf的大文件,但我的ppm图像不大于500×500像素……

为了能够继续阅读,我能做什么/应该做什么?

谢谢您的帮助!

我猜你是在Windows上; 值为0x1b的字节表示Windows上文本文件的“文件结尾”。 (参见注释;这种解释是错误的,但解决方案有效,大概是因为数据中有一个0x1a )。

您应该以二进制模式打开文件:

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

这将成功读取所有字节。 (它还会读取行尾标记的\r\n 。)