On 9/25/19 3:13 PM, Jorgen Grahn wrote:
> On Wed, 2019-09-25, Paavo Helde wrote:
>> On 25.09.2019 7:20, Richard wrote:
>>> [Please do not mail me a copy of your followup]
>>>
>>> I'm not talking about printing numbers in base 2.
>>>
>>> I have a program that outputs ESC sequences for a terminal. I don't
>>> want Windows to translate '\n' into '\r\n'. If I construct an
>>> ofstream with std::ios_base::binary, then that's what I get. However,
>>> if I try to use std::cout, I always get a stream that's been opened in
>>> text mode and I get \n -> \r\n in the output.
>>>
>>> Is there a way to switch std::cout to behave as if I did
>>> std::ofstream(fileName, std::ios_base::binary)?
>>
>> Sure, this should do the trick:
>>
>> #include <iostream>
>> #include <io.h>
>> #include <fcntl.h>
>>
>> int main() {
>> fflush(stdout);
>> _setmode(_fileno(stdout), _O_BINARY);
>> std::cout << "\n";
>> }
>>
>> This solution is Windows/MSVC-specific, but so is the problem.
>
> Is it, really? The language is aware of the text/binary distinction,
> so I bet it specifies which one std::cout is, and whether you can
> portably do anything about it.
"The object cout controls output to a stream buffer associated with the
object stdout, declared in
<cstdio> (30.11.1)." (30.4.3p3)
"1 The contents and meaning of the header <cstdio> are the same as the C
standard library header <stdio.h>." (30.11.1p1)
" stderr
stdin
stdout
which are expressions of type ‘‘pointer to FILE’’ that point to the FILE
objects associated, respectively, with the standard error, input, and
output streams." (C2011 7.21.1p3).
The C standard defines two functions that can set the mode of a stream:
fopen() and freopen() (Annex K adds fopen_s() and freopen_s()). Since
stdout starts out already open, freopen() is your only option. For
freopen(filename, mode, stream), section 7.21.5.4 of the C standard says:
"2 The freopen function opens the file whose name is the string pointed
to by filename and associates the stream pointed to by stream with it.
The mode argument is used just as in the fopen function. 272)
3 If filename is a null pointer, the freopen function attempts to change
the mode of the stream to that specified by mode, as if the name of the
file currently associated with the stream had been used. It is
implementation-defined which changes of mode are permitted (if any), and
under what circumstances."