2

I have two c++ exes communicating over iostream. First exe sends a stream of chars (or bytes) and second intercepts this and decodes them.

exe1.exe emits chars:

void main()
{
    for (int i = 0; i < 256; ++i)
    cout << static_cast<char>(i);
}

exe2.exe takes them in:

void main()
{
    FILE* pipe = _popen("exe1.exe", "rb");
    while (!feof(pipe))
        cout << static_cast<int>(fgetc(pipe)) << endl;
    _pclose(pipe);
}

One would expect to receive 256 values in serial order as so: 0,1,2,3,4,5,6,7,8,9,10,11,12,13...

But one gets 0,1,2,3,4,5,6,7,8,9,13,10,11,12,13...

There is a problem at 10, where you can see an additional 13 before it. Possibly cout wants to be helpful by adding an extra carriage return before a \n char. But it is annoying when one wants to transfer pure bytes between two processes. Yes, cout is for human readability, but is there a way to tell cout or printf to not do that? Or to use another stream which is not intended for humans to read?

ssg
  • 83
  • 6

1 Answers1

0

Character 10 is the ASCII LF, which is treated as a line break on most platforms. On Windows specifically, the standard line break is a 13 10 (CRLF) sequence. C++ stream implementations are smart enough to know that and will convert character 10 to 13 10 on output when operating in text mode. If you don't want that to happen, you have to put the output stream into binary mode instead.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770