开发者

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

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 wr开发者_运维问答itten 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.


You're using operator<<() which outputs formatted text to a stream. You thus write plaintext into a binary file, which sort of defeats the purpose of writing in binary-mode. Try opening the output file in a text editor and see for yourself.

You have two choices: either write in text-mode and delimit your values with whitespace (because writing in binary-mode is misleading when you use formatted output), or use the stream's write() method with casting.

f.write(reinterpret_cast<char*>(&k), sizeof(int));
// ...
f.read(reinterpret_cast<char*>(&k), sizeof(int));

I personally prefer writing in text-mode. It means having a cleaner code and a portable output file. If you must you can compress the file.


operator<< produces formatted text as its output, so yes, you'll need to put some sort of whitespace between the numbers to separate them. Otherwise, they'll all run together into one huge string of digits, and when you read them back in, it'll continue to read digits as part of a number until it overflows -- e.g. if you wrote 1 three times, it would read back in as 111.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜