iostreams, std::cout and binary

Simson Garfinkel simsong at acm.org
Tue Nov 15 17:20:57 UTC 2011


I have the need to send binary data to std::cout.  The hack that I've previously used on Windows is to include this line in my main.cpp file:

#ifdef WIN32
// Allows us to open standard input in binary mode by default                                                                                     
// See http://gnuwin32.sourceforge.net/compile.html for more                                                                                      
int _CRT_fmode = _O_BINARY;
#endif

Sadly, this does not seem to work for std::cout

I tried this:

	std::ofstream f;
	f.open("CON",std::ios_base:binary)
	f << "this is a bare nl: \n  see? No CR.\r\n";

But that didn't work. Actually, it was kind of weird --- the stdout couldn't be redirected --- it went to the console. And it didn't come out in binary.

I understand that I can open an iostream with the ios_base::binary flag. However it is not clear to me how to open stdout.


The _CRT_fmode trick does seem to work for a write() that I have to file descriptor 1, however.

	const char *buf = "this is a newline: \n  and this is both a cr and a newline: \r\n";
	write(1,buf,strlen(buf));

Can someone tell me:

1. Is it possible to write binary to std::cout ?
2. Is there a way to "re-open" std::cout?

Thanks,

Simson





More information about the mingw mailing list