When I am trying to operate a text file I hope to set the end-of-line character as what is preferred on the destination OS, say, LF in linux text files and CRLF in windows text files.
Related questions
According to question C++: Is there a standard definition for end-of-line in a multi-line string constant? the eol character depends on the characters in source files. That means, when i use
std::ofstream out{"hello.txt"};
out << R"(Hello
World)" << std::endl;
the eol characters in "hello.txt" maps to a single '\n' character, even when the source file is stored in windows text format.
According to questions Detect Windows or Linux in C, C++ and Standard #ifdef for Cygwin, I may use
#if defined(_WIN32) || defined(__CYGWIN__)
#define END_OF_LINE "\n\r"
#else
#define END_OF_LINE "\n"
However, i have no idea how to put these codes into the former code segment.
Java solution
In java, use
System.getProperty("line.separator");
will return the corresponding end-of-line characters.
JDK 7 replaces the above line with System.lineSeparator()
, which is more efficient.
C++ solution?
C++17 filesystem provides a constant: std::filesystem::path::preferred_separator
to tell the path separator on various OS platforms. I think this is a good form.
Is there any existing facilities in C++17 or newer standards providing such convenience as std::xxx::preferred_eol_separator
?