问题
I would like to know if it is possible that an utility yields binary data (i.e. graphical images) and outputs them through IO console, while another application, instructed about the nature of those data and informed of the number of the incoming bytes, is able to read it from IO console.
回答1:
Yes, it is possible. While it's true that often stdin
/stdout
are meant to be text there are many programs that are designed to get binary input or write binary output from standard I/O channels.
The only thing you should pay attention is that normally stdout
/stdin
are opened in text mode under Windows, so you should switch them to binary mode to avoid character translation.
To set binary mode on stdin
/stdout
on Windows you need to use the _setmode call:
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
int main( void )
{
int result;
// Set "stdin" to have binary mode:
result = _setmode( _fileno( stdin ), _O_BINARY );
if( result == -1 )
perror( "Cannot set mode" );
else
printf( "'stdin' successfully changed to binary mode\n" );
}
Note also to pay attention to file buffering. Often programs will flush the buffer on newlines ONLY when the output is to an interactive console and not when it's another process. So if you need synchronizaton remember to call fflush
after writing a message because otherwise the other process will not be able to get the data.
回答2:
You could Base 64-Encode/Decode the data. This will avoid the need to send pure "bits" over the standard input/output stream.
回答3:
You can use traditional socket or lighter named pipe for this kind of thing.
回答4:
If the process is to be hosted within another process that will capture your stdout from the process that writes binary data then there is no need to encode it. In that case you can write the raw binary data to the output and be done with it. This is for example how the image writing dot
tool from graphviz works, it doesn't encode it's input by default. These kinds of tools are also pretty easy to pipe to a file by the use of >
in the command shell.
Only if the output from the data is going to be seen on the console are you going to need to encode it. It's not a very good idea to print the contents of say an image file.
回答5:
You can do it if you choose an appropriate encoding, as the console is a text stream. Use for example Base64 encoding for your binary data and it will work fine. Another alternative is the "Quoted-printable" format. You end up of course with more bytes than the original binary data, but IMHO the only way to do it safely using the console.
来源:https://stackoverflow.com/questions/9554252/c-c-is-it-possible-to-pass-binary-data-through-the-console