tags:

views:

151

answers:

2

Different platforms use different line separator schemes (LF, CR-LF, CR, NEL, Unicode LINE SEPARATOR, etc.). C++ (and C) make a lot of this transparent to most programs, by converting '\n' to and from the target platform's native new line encoding. But if your program needs to determine the actual byte sequence used, how could you do it portably?

The best method I've come up with is:

  1. Write a temporary file in text mode with just '\n' in it, letting the run-time do the translation.
  2. Read back the temporary file in binary mode to see the actual bytes.

That feels kludgy. Is there a way to do it without temporary files? I tried stringstreams instead, but the run-time doesn't actually translate '\n' in that context (which makes sense). Does the run-time expose this information in some other way?

+5  A: 

I'm no C/C++ expert, but there doesn't appear to be anything in the standard library that will directly give you the line separator. The translation is handled transparently by the text-mode file functions.

Even though you feel your approach is "kludgy", it is probably the simplest and most reliable, since you are really testing what line separator is used and written out. And is portable, since you are using standard library functions to write and read the file.

mdma
A: 

Just a basic idea (works on Mac) but it might actually work on Windows:

const std::string& getEndOfLine()
{
    std::stringstream streamEndOfLine;
    streamEndOfLine << std::endl;
    std::string strEndOfLine = streamEndOfLine.str();
    return strEndOfLine;
}
Vincent Robert
Isn't this just restating the failed method from the question? Doesn't it suffer from the problem that the translation may only happen when reading and writing _files_ in text mode?
Charles Bailey
No, because the failed method was using "\n" while I am suggesting using std::endl which should be the platform end of line.
Vincent Robert