-3

I try to write 32bit integers to file using an ostream. I'm using the << operator:

ostream file;
map<unsigned char, int32_t> histogram;
//… 
file << reinterpret_cast<char*>(&histogram[i]);  

It works well except for the last number (in my case 11328 which would be 40 2C 00 00 in binary) but instead only 40 2C is written into the file.

It is the same number but when I'm going to import the file again I want to asume that every number is coded in 32bit.

What did I do wrong?

kanedo
  • 75
  • 6
  • 1
    A little bit more code, the sample input, the expected outout, and the sample output will be useful in diagnosing the problem. – R Sahu Jun 18 '14 at 16:11
  • You are lucky that this worked at all. – T.C. Jun 18 '14 at 16:12
  • 1
    So you want to write a binary file, don't you? Then converting to pointers is the wrong way to do this. – stefan Jun 18 '14 at 16:26

2 Answers2

4

You are using the operator<<(ostream&, const char *) overload for something that is plainly not a C-style null-terminated string, which results in undefined behavior.1

In the case of 40 2C 00 00, the function interpreted the zero-byte as a null terminator, so it only printed the first two bytes.

When you want binary I/O, use ostream::write(). << is for formatted I/O.


1) More precisely, you are in undefined-behavior land whenever the last byte of the integer isn't zero - i.e., whenever this prints out all 4 bytes you want to print.

T.C.
  • 133,968
  • 17
  • 288
  • 421
  • With `ostream::write()`, he'll have to format the data himself. There's a reason it takes a `char const*`, and not a `void const*`; if you need a `reinterpret_cast`, you're doing something non-portable. – James Kanze Jun 18 '14 at 16:44
0

When you use file << reinterpret_cast<char*>(&histogram[i]);, in fact, it think you want to output a C style string. So it will stop outputting when meeting a '\0'. So your result is 40 2C.

You could try fwrite() function in stdio.h.

tianzhi0549
  • 479
  • 2
  • 5
  • 12
  • I'm sorry.I recommended fwrite() because I'm unfamiliar with the ostream class.But I want to know why fwrite() isn't a good recommendation for C?Thanks.@JamesKanze – tianzhi0549 Jun 18 '14 at 16:51