Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get platform specific end of line character in C++/Qt

Is there anything for getting right end-of-line symbol for any platform? I mean, I can use \n for Windows and Unix if I want to write EOL to file, but there is also \r\n and this would be significant if I'll do searching in binary data.

So, I need something like Environment.NewLine in C# and it should be some class and not trick with #ifdef Q_OS_WIN32....

Use case is reading from QTextStream all data and split it by new line. Anyway, if QTextStream or QString::split is smart enough to handle \n correctly on any platform, I want to know about thing I asked.

like image 863
cassandrad Avatar asked Oct 31 '22 19:10

cassandrad


2 Answers

Try

QString::split(QRegularExpression{R"-((\r\n?|\n))-"})

This uses a C++11 raw string literal to create a regex that matches all three possibilities:

  • CR only (Mac)
  • CR+LF (Win)
  • LF (Unix)

If you can not use C++11, you will have to manually escape the regex:

"(\\r\\n?|\\n)"

That should do the trick.

like image 134
fer-rum Avatar answered Nov 15 '22 03:11

fer-rum


When you are writing a file in text mode, the "\n" character should be reinterpreted as whatever is appropriate for that system. For Windows, that means CRLF (carriage return, line feed), on Unix, it's just LF alone, and the Macintosh standard is a CR by itself.

When you are reading, be ready to end a line at either one of those characters, but if you find a carriage return, check to see if there is a line feed immediately after it, and if there is, consider it part of the same line.

like image 37
Logicrat Avatar answered Nov 15 '22 04:11

Logicrat