views:

56

answers:

2

I want serialize object to binary file using operator "<<", but when I serialize, for example, int fields, I obtained it's symbolic representation:

ofstream out("file", ios::out | ios::binary);
int i=0xAA;
out << i;

And output:

0x31 0x37 0x30

i.e. (0xAA -> 170)

170

If I use write function, all ok:

out.write((char*)&i,sizeof(int));

Output:

0xAA 0x00 0x00 0x00

But can I use << instead write function, to serialize object? Like:

out << obj.field1 << obj.field2; // etc.
+2  A: 

For std::ostream and derived classes, operator<< is a formatted output function. write(), on the other hand, is an unformatted output function. So with ostreams, the answers is no.

On the other hand you could consider using Boost.Serialization, with which you can serialize to binary archives using << operator.

usta
+1  A: 

First, a warning: You do know that the bytes within an int, or anything similar, depends on your compiler, computer, and operating system, right? Other systems might output bytes 0x00 0x00 0x00 0xAA for your example above, or something else entirely. Which means that if you send those bytes to a different computer and attempt to read them, you won't necessarily get your original int back.

Anyway. If you just want to spit out entire objects, one way to set this up would be to just define serialization for your class(es) and/or struct(s) by overloading operator<<:

std::ostream& operator<<(std::ostream& out, const MyClass& obj) {
  out.write(reinterpret_cast<const char*>(&obj.field1),
            sizeof(obj.field1)); // or something better defined
  // ...
  return out;
}

ofstream out("file", ios::out | ios::binary);
out << obj1 << obj2;
aschepler
I've been thinking about this approach, i.e. overloaded operator << like wrapper over write function. Byte order not critical, as I will use objects only on the same platform.
StNickolay