what does std::endl represent exactly on each platform?
Thinking about UNIX, Windows and Mac and an output stream (both binary and text),
What does std::endl
represent, i.e. <CR><LF>
, <LF>
or <CR>
? Or is it always the same no matter what platform/compiler?
The reason I'm asking is that I'm writing a TCP client that talks a protocol that expects each command to end in <CR><LF>
. So I'm wondering whether to use std::endl
or "\r\n"
in my streams.
EDIT: Ok, so one flushes the buffer and anothe开发者_开发技巧r doesn't. I get that. But if I'm outputting text to a file, is '\n'
equal to <LF>
or does it convert to <CR><LF>
on Windows and <LF>
on Unix or not? I don't see a clear answer yet.
The code:
stream << std::endl;
// Is equivalent to:
stream << "\n" << std::flush;
So the question is what is "\n" mapped too.
On normal streams nothing happens. But for file streams (in text mode) then the "\n" gets mapped to the platfrom end of line sequence. Note: The read converts the platform end of line sequence back to a '\n' when it reads from a file in text mode.
So if you are using a normal stream nothing happens. If you are using a file stream, just make sure it is opened in binary mode so that no conversion is applied:
stream << "\r\n"; // <CR><LF>
The C++ standard says that it:
Calls os.put(os.widen(’\n’) ), then os.flush()
What the '\n' is converted to, if it is converted at all, is down to the stream type it is used on, plus any possible mode the stream may be opened in.
Use stream << "\r\n"
(and open the stream in binary mode). stream << std::endl;
is equivalent to stream << "\n" << flush;
. The "\n" might be converted to a "\r\n" if the code runs on Windows, but you can't count on it -- at least one Windows compiler converts it to "\n\r". On a Mac, it's likely to be converted to "\r" and on Unix/Linux and most similar systems, it'll be left as just a "\n".
Quoted from the accepted answer on a related question:
The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for.
The only difference is that std::endl flushes the output buffer, and '\n' doesn't. If you don't want the buffer flushed frequently, use '\n'. If you do (for example, if you want to get all the output, and the program is unstable), use std::endl
In your case, since you specifically want <CR><LF>
, you should explicitly use \r\n
, and then call std::flush()
if you still want to flush the output buffer.
Looks like your question got munged. Each command ends in []? For an over-the-wire protocol, I'd suggest using a delimiter that doesn't vary by platform. std::endl could resolve to '\r\n' or '\n\r' depending on the platform.
精彩评论