Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does printf create windows line endings?

Tags:

c

printf

mingw

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?

like image 537
ditoslav Avatar asked Jan 25 '23 16:01

ditoslav


1 Answers

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.

like image 198
Bart Friederichs Avatar answered Feb 11 '23 20:02

Bart Friederichs