0

I need to print a newline character to a file with a C program running in windows and compiling with MinGW. However, it has to print \n only, instead of \r\n.

Take for example the following program:

#include <stdio>

void main() {
    FILE * fid = fopen("out.txt", "w");
    fprintf(fid, "\n");
    fclose(fid);
}

Reading the created file in Matlab with the command:

text = int32(fileread('out.txt'))

Yields:

1x2 int32 row vector

13 10

Yet, somehow, I need it to print only 10 and not the 13 (=\r) character.

Mefitico
  • 816
  • 1
  • 12
  • 41

1 Answers1

1

Open the file in binary mode so that the NL to CRLF mapping used with text files is not done for you. So:

const char filename[] = "out.txt";
FILE *fid = fopen(filename, "wb");
if (fid == 0)
{
    fprintf(stderr, "Failed to open file %s for binary writing\n", filename);
    exit(EXIT_FAILURE);
}

(assuming you include <stdlib.h> too). I don't recommend void main() — the correct standard definition for no arguments is int main(void), and then you could use return 1; instead of exit(EXIT_FAILURE); to report the error to the environment. See also What should main() return in C and C++? for more information.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278