ditoslav
ditoslav

Reputation: 4872

Why does printf create windows line endings?

So I'm trying to copy (and later modify) a .ppm file. I'm on Windows 10 using mingw g++. The original file is LF only but the one created with my program has CRLF which breaks the .ppm file. I'm not doing \r\n anywhere but it still gets outputted.

FILE *fp;
FILE *dest;

char magicNumber[3];
int width, height, depth;
unsigned char red, green, blue;
unsigned char* buff;

printf("Hello, World!\n");


fp = fopen("lenna.ppm", "r+");

fscanf(fp, "%s", magicNumber);
fscanf(fp, "%d %d %d", &width, &height, &depth);
printf("%s %d %d %d nums\n", magicNumber, width, height, depth);


dest = fopen("lena2.ppm", "w+");
fprintf(dest, "%s\n%d %d\n%d", magicNumber, width, height, depth);

Results in

enter image description here

WHY?

I want to only have LF. How do I do that?

Upvotes: 4

Views: 926

Answers (1)

Bart Friederichs
Bart Friederichs

Reputation: 33511

Open your file in binary mode:

fopen("lena2.ppm", "wb+");

From the docs:

In text mode, carriage return-line feed combinations are translated into single line feeds on input, and line feed characters are translated to carriage return-line feed combinations on output.

Upvotes: 8

Related Questions