Write set of integers to std::ofstream and be able to read them back

Posted by bndu on Stack Overflow See other posts from Stack Overflow or by bndu
Published on 2010-03-19T14:43:18Z Indexed on 2010/03/19 15:41 UTC
Read the original article Hit count: 144

Filed under:
|
|
|

Hello,

I need to write a bunch of unsigned integers to std::ofstream in binary mode:

std::ofstream f;
f.open("some path", std::ios::out | std::ios::binary);
// some loop
{
  unsigned int k = get_k(); // may product numbers from 0 to 65535
  f << k;
}
f.close();

They are written to the output file "as is" w/o any delimiter. So when I'm trying to read them back (expecting to get what I wrote) using std::ifstream I get very strange values. What I'm doing wrong?

Or I should to put ' ' (space) to the stream after any added number to separate them?

Thanks.

© Stack Overflow or respective owner

Related posts about c++

Related posts about ofstream