When writing binary data, you can not use in >> x
or out << x
, since those are "text read and write" functions.
So, instead of:
out<<unsigned char(c);
out<<int(n);
you will need to use:
out.write(&c, sizeof(c));
out.write(reinterpret_cast<char*>(&n), sizeof(n));
To explain in more detail:
n = 12345;
out << n;
will output 12345
as individual characters.
If you output this:
c = '1';
n = 2345;
out << c << n;
then the output will also look like 12345
.
On the other hand, in >> c
will skip spaces, so
c = ' ';
n = 1234;
out << c << n;
in >> c >> n;
will have c == '1'
and n==234
after the input.