Find the system line terminator
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?
source to share
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'
(aschar
for streamschar
); -
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)
source to share