Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

file-io

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.

like image 759
challengerTA Avatar asked Dec 21 '22 22:12

challengerTA


2 Answers

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.

like image 159
Hasturkun Avatar answered May 16 '23 06:05

Hasturkun


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?

like image 35
pj_ Avatar answered May 16 '23 07:05

pj_