0

i have pointer to data buffer.
when i write PPM image using string (ASCII), it's written successfully without any distortion. https://i.stack.imgur.com/TYAFY.png
but when i do the same thing but write binary data instead it gets distorted. https://i.stack.imgur.com/aaL72.png

I'v spent hours and i still don't know what is the problem. this is the code for the string writing

FILE *f;
int i;
f = fopen(filename,"w");
if (f == NULL) {
    printf("cant open the file \n");
}
fprintf(f, "P3\n%d %d\n%d\n", xsize, ysize, 255);
for (i = 0; i < ysize * xsize * 3; i++){
    fprintf(f, "%u\n", buf[i]);
}
fclose(f);

this is the code for the binary writing

FILE *f;
int i;
f = fopen(filename,"w");
if (f == NULL) {
    printf("cant open the file \n");
}
fprintf(f, "P6\n%d %d\n%d\n", xsize, ysize, 255);
for (i = 0; i < ysize * xsize * 3; i++){
    fwrite(buf + i, 1, 1, f);
}
fclose(f);

please help!

DaBler
  • 2,695
  • 2
  • 26
  • 46
  • 3
    Does `f = fopen(filename,"wb");` help? – DaBler Aug 08 '21 at 11:15
  • The explanation can be found, e.g., in [this question](https://stackoverflow.com/questions/20863959/difference-between-opening-a-file-in-binary-vs-text). – DaBler Aug 08 '21 at 12:01

1 Answers1

0

for people who had the same problem. just make sure to use

fopen("filename.ext", "wb")

instead of

fopen("filename.ext", "w")

this is an explanation for why to use "wb" for binary instead of "w".
Difference between opening a file in binary vs text