fprintf不断添加我不想要的额外字符.我不能阻止这个吗?

cha*_*rTA 4 c file-io

我试图写出一个具有以下结构的图像文件:

P5      //magic number
512 512 //dimension of image
255     //max value per pixel
[Image Data.....]
Run Code Online (Sandbox Code Playgroud)

标准说在最大值之后应该有空格或换行符,然后是图像数据.无论出于何种神秘原因,下面的代码>始终<在标题的末尾添加2个字符(回车和换行).它将每个像素偏移1.

这是我做的:

   FILE *outfile; 
   outfile = fopen(filename,"w");
   int i =0, j =0;
   if(outfile==NULL || outfile == 0){
   printf("Output Failed\n");
   return;
   }
   //print header first 
   fprintf(outfile, "P5\r%d %d\r255",width,height);  
   //print out data now, all one line.
   for(i = 0; i<height; i++){
         for(j=0;j<width;j++){
              fprintf(outfile, "%c",pic[j][i]);
         }
   }

   fclose(outfile);
   printf("output to %s complete.\n", filename);          
   return;
Run Code Online (Sandbox Code Playgroud)

我在这里缺少一个C微妙的东西吗?如何让它不打印额外的字符?我做了一些实验,但我很茫然.谢谢你的时间.

Has*_*kun 9

您必须在Windows上,并且您的输出文件以文本模式打开.更改fopen(filename,"w")为fopen(filename,"wb")以二进制模式打开文件,问题应该消失.