Search code examples
c++cprintfoutputeol

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.


Solution

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