feof()和fscanf()在将字节1b扫描为字符后停止工作。是因为它是ascii中的“ESC”吗?我能做什么? [英] feof() and fscanf() stop working after scanning byte 1b as a char. Is it because it is 'ESC' in ascii? What can I do?

查看:182
本文介绍了feof()和fscanf()在将字节1b扫描为字符后停止工作。是因为它是ascii中的“ESC”吗?我能做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

以下几乎是我的代码:



//所有包含在那里,..., p>

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

finput = fopen(my.ppm,r);

/ *
我读取P6 numRows的代码numColumns 255\\\


...假设该部分工作得很好
* /


while(!feof(finput))
{
num [0] = fscanf(finput,%c,& r); //num [] =部分用于调试
num [1] = fscanf(finput,%c,& g);
num [2] = fscanf(finput,%c,& b);


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



}
return 0; //或任何...
}

由于某种原因,fscanf开始返回-1读取ESC字节(但读取它不会返回-1)



所以样本输出将是:



1
-1
-1






另一方面我阅读了while(!feof())总是错误的,而有关fscanf的大文件,但是我的ppm图像不大于500x500像素...



感谢您的帮助!

解决方案

我猜你在Windows上一个字节,值为$ code> 0x1b 表示Windows上文本文件的文件结束。 (请参阅注释;这个解释是错误的,但解决方案有效,大概是因为数据中有一个 0x1a



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

  fopen(my.ppm,rb); 

这将成功读取所有字节。 (它还将读取$ code> \r 和行尾标记的 \\\
。)


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

这篇关于feof()和fscanf()在将字节1b扫描为字符后停止工作。是因为它是ascii中的“ESC”吗?我能做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆