Since Windows uses CRLF as native line endings, one might expect that code like this
#include <windows.h>
#include <string.h>
int main() {
HANDLE stdout = GetStdHandle(STD_OUTPUT_HANDLE);
char* msg = "Line1\nLine2\nLine3\nLine4\nLine5\n";
DWORD written = 0;
WriteFile(stdout, msg, strlen(msg), &written, NULL);
return 0;
}
would produce the following output:
line1
Line2
Line3
Line4
Line5
But it produces:
Line1
Line2
Line3
Line4
Line5
Are the LF translated within cmd to also move the cursor to the first line? Because they do not appear to be translated to CRLF when output is redirected to a file (I originally tried WriteConsoleA only to observe that it does not support redirection).
Is it OK to only use LF and not CRLF in cross-platform programs then? Is this behaviour given for all versions of windows or do some of them produce the "staircase" pattern described above?
CodePudding user response:
The console standard output buffer has ENABLE_PROCESSED_OUTPUT|ENABLE_WRAP_AT_EOL_OUTPUT
by default.
\r
alone just returns to the start of the line allowing you to overwrite yourself. \n
is treated as \r\n
for unknown reasons (Compatibility? Source portability?). NT4 does it, XP does it, 8 does it and 10 does it.
If you turn off ENABLE_PROCESSED_OUTPUT
with SetConsoleMode
then neither \r
nor \n
are special and WriteFile
will print them as symbols to the console instead.
CodePudding user response:
Your expectations are exactly on target. And you are correct - that isn't what you see. And @IInspectable is correct that you can't open devices via the Windows CreateFile API in text mode.
And yet, you see what you see.
If you check out this, you will find that Windows contains some console mode settings that aren't apparent when you are reading the API function descriptions. In particular, there is an ENABLE_PROCESSED_OUTPUT mode that is on by default. When this is on it enables special processing to handle '\n' line endings and other things.
Note that this is for console I/O only. For actual file I/O Windows API calls do no translations. On the other hand, the C library function fopen allows a file to be opened it text or binary mode. Binary mode does no translation, but text mode enables special handling for \n
on Windows systems.
I understand that this is also handled similarly for consoles on POSIX systems where "\n" and not "\r\n" is the official standard line ending.