3

I want to generate on Windows a file (script) for UNIX. So I need to output just LF characters, without outputting CR characters.

When I do fprintf(fpout, "some text\n");, character \n is automatically replaced by \r\n in the file.

Is there a way to output specifically just \n (LF) character?

The language is C++, but the I/O functions come from C.

Serge Rogatch
  • 13,865
  • 7
  • 86
  • 158
  • A workaround would be to use [putchar()](http://www.cplusplus.com/reference/cstdio/putchar/), if no easy solution exists. – gsamaras Nov 26 '18 at 12:42

1 Answers1

9

You can open the file in binary mode, e.g.

FILE *fpout = fopen("unixfile.txt", "wb");

fprintf(fpout, "some text\n"); // no \r inserted before \n

As a consequence, every byte you pass to fprintf is interpreted as a byte and nothing else, which should omit the conversion from \n to \r\n.

From cppreference on std::fopen:

File access mode flag "b" can optionally be specified to open a file in binary mode. This flag has no effect on POSIX systems, but on Windows, for example, it disables special handling of '\n' and '\x1A'.

lubgr
  • 37,368
  • 3
  • 66
  • 117
  • 1
    This question is an awesome coincidence, I just read about exactly this _yesterday_ in Arthur O'Dwyer's STL book. The author also made no effort to hide his opinion on how Windows handles newlines. – lubgr Nov 26 '18 at 12:53