开发者

fprintf keeps putting in extra characters I don't want. Can't I stop this?

Im trying to write out an image file that has the following structure:

P5      //magic number
512 512 //dimension of image
255     //max value per pixel
[Image Data.....]

The standard says after max value there should be a whitespace or newline, then the image data. For whatever mysterious reason, the code below >always< adds in 2 characters at the end of the header (A carriage return and line feed). Which shifts every pixel off by 1.

Here's what I do:

   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;

Is there a C subtlety that I'm missing here? How do I get 开发者_开发问答it to not print that extra character? I did a few experiments and I'm at a loss. Thanks for your time.


You must be on windows and your output file is opened in text mode. Change fopen(filename,"w") to fopen(filename,"wb") to open the file in binary mode and the problem should go away.


I don't see 2 chars after the header when I run the above code.

I don't even see 1 char. The data starts at the very next byte after the "255" ending the header.

Is it possible that your data has pic[0][0] as a carriage return char and pic[1][0] as a line feed char?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜