Does the C++ standard allow reading and writing arbitrary binary data via stdin/stdout?

Viewed 196

I'm still confused about what exactly the C++17 standard says about what is allowed to be read in from and written to standard in and out.

Does a program invoke undefined behavior if it accepts arbitrary binary data via standard in or outputs arbitrary binary data to standard out (even though many programs do that in practice)?

2 Answers

stdio is completely neutral regarding the data transported over it.

If it weren't, it would break things like I/O redirection. If you couldn't send raw binary data over stdio you couldn't use insert tools like a gzip compressor into a shell pipe.

The question is about the standard, so I think the answer given to this question applies to yours too:

The standard is not always as coherent as we would like, since it is a very large document, written (in practice) by a number of different people, and despite all of the proof-reading that does occur.

As the same answer suggests, it's hard to say what is ill-formed.

My understanding is that the standard is simply not explicit about that, but there are other language features (as demonstrated by example by datenwolf) that imply it is not ill-formed, whatever it means:

the simple fact that STDIN and STDOUT are file handles means they can be opened and read/written in binary mode.

Related