Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ print custom EOL

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.

like image 746
Serge Rogatch Avatar asked Feb 04 '26 23:02

Serge Rogatch


1 Answers

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'.

like image 88
lubgr Avatar answered Feb 06 '26 11:02

lubgr