MS documentation says I should be able to suppress the conversion of LF to CRLF when writing to stdout by using _setmode. That doesn't seem to happen.
This console program (VS2005) doesn't give the expected output. Each new word printed starts at the beginning of a line. I expect it to look like this:
one
two
three
four
but I get:
one
two
three
four
// consoletest.cpp : Defines the entry point for the console application.
//
#include
"stdafx.h"#include
<stdio.h>#include
<fcntl.h>#include
<io.h>#include
<string.h>int _tmain(int argc, _TCHAR* argv[])
{
int result;
int len;
int ch;
int count;
char str[] = "one\ntwo\nthree\nfour\n";
result = _setmode(_fileno(stdout), _O_BINARY);
if (result == -1)
perror("setmode failed\n");
else if (result == _O_BINARY)
printf("mode was binary\n");
else if (result == _O_TEXT)
printf("mode was text\n");
len = (int)strlen(str);
#if
0for (int i = 0 ; i < len ; ++i) {
// putchar(str
);
_fputchar(str
);
}
#endif
//count = _write(_fileno(stdout), str, len);
printf(str);
result = _setmode(_fileno(stdout), _O_TEXT);
if (result == -1)
perror("setmode failed\n");
else if (result == _O_BINARY)
printf("mode was binary\n");
else if (result == _O_TEXT)
printf("mode was text\n");
ch = getchar();
return 0;
}

_setmode problems
ernisj
kzu
Actually, It happens. Let me try to explain:
Standard Output Stream(stdout) is NOT equal to the Console(screen and keyboard). There are typically 2 steps for a program to display a string to console.
1. The program emit the characters to the standard output stream.
2. Display the characters in standard output stream to console.
In step 1: By default, standard output stream use text mode. This means '\n' in your program will be translated and stored as '\r\n' into standard output stream. Use _setmode you can switch the standard output stream to binary mode, which means no translation happens, '\n' will stored exactly as '\n' in the standard output stream.
In step 2: It is console who can determine how to display '\n' and '\r\n'. In this case, both LF and CR-LF are displayed as a CR-LF. So no matter whether binary mode is used in stdout or not, the things we can see from the screen is always the same.
Still not clear see this table:
Code
Standard output stream
Console
Set to binary mode
‘\n’
‘\n’
Display a newline
Set to text mode
‘\n’
‘\r\n’
Still display a newline
So the _setmode function DO suppress the conversion of LF to CRLF when writing to stdout as the document stated.
So you should use windows API if you want to control the console. All the console APIs are listed here:http://msdn2.microsoft.com/en-us/library/ms682073.aspx, take a look at it. Honestly, I haven't been able to figure out which one can help us, I suspect it is not supported and have to use another way to achieve this.