Find the system line terminator

Is there a header file somewhere that stores the line endings for the system (so without any, #ifdef

it will work on all platforms, MAC, Windows, Linux, etc.)?

+3


source to share


4 answers


No, because he is \n

everywhere. This expands to the correct newline character when you write it to a text file.



+3


source


You have to open the file in "text mode" (that is, "don't use binary") and the newline is always '\n'

, regardless of the original file. The C library will translate any native character (s) pointing to newline characters as '\n'

needed [ie, reading / writing text files]. Note that this also means that you cannot rely on "counting the number of characters read and using that to" search this place ".

If the file is binary, then newlines are not newlines.

And unless you plan on working on really ancient systems, and you REALLY want to do this, I would do:



#ifdef __WINDOWS__    // Or something like that
#define END_LINE    "\r\n"
#else
#define END_LINE    "\n"
#endif

      

This won't work for macOS prior to macOS X, but surely nobody else is using pre-MacOS X hardware anymore?

+2


source


There is nothing in the standard library to get the current platform line terminator.

The closest API looks like

char_type  std::basic_ios::widen(char c);

      

It converts c to its current locale equivalent "( cppreference ). I pointed it out with the documentation std::endl

, which" inserts an end character into the os's output sequence and flushes it as if it were calling os.put(os.widen('\n'))

, then os.flush()

"( cppreference ).

In Posix,

  • widen('\n')

    returns '\n'

    (as char

    for streams char

    );
  • endl

    inserts '\n'

    and flushes the buffer.

On Windows, they do the same. Actually

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ofstream f;
    f.open("aaa.txt", ios_base::out | ios_base::binary);
    f << "aaa" << endl << "bbb";
    f.close();
    return 0;
}

      

will result in a file using '\n'

only as a line delimiter.

As others have pointed out, when a file is opened in text mode (the default), it '\n'

will be automatically converted to '\r' '\n'

in Windows.

(I rewrote this answer because I incorrectly assumed it was std::endl

translated to "\r\n"

on Windows)

+1


source


Posix requires this to be \ n. Therefore, if _POSIX_VERSION is defined, it is \ n. Otherwise, in the special case, only non-POSIX OS will be used and you're done.

+1


source







All Articles