tags:

views:

247

answers:

6

This is a C++ question. I have a class that contains a string:

class MyClass{
public:
std::string s;
};

And I have an array of MyClass objects:

MyClass * array = MyClass[3];

Now I want to write the array as binaries into a file. I cannot use:

Ofstream.write((char *)array, 3 * sizeof(MyClass))

because the size of MyClass varies.

How can I use Ofstream.write to achieve the purpose? Many thanks.

A: 

Open the stream in binary mode:

std::fstream filestream( "file.name", std::ios::out | std::ios::binary );
Klaim
+1  A: 

Write an insertion operator for MyClass, like this, that writes out its members to the stream one by one. Then make a loop that walks your array, writing each member to the stream. Remember to write out the array size at some point too, so you know how many members to read when you read the file back.

And, as Klaim says, make sure you open the stream in binary mode.

moonshadow
+1  A: 

A good way of doing this would be to override the << operator for MyClass:

ostream& operator << (ostream& output, const MyClass& myClass)
{
    return output << myClass.Value;
}

You can then simply serialise the strings out of MyClass directly into the file stream:

std::fstream fileStream("output", std::ios::out|std::ios::binary);

for (int i = 0; i < 3; ++i)
    fstream << array[i];
Alan
+7  A: 
Beh Tou Cheh
"for mc : 0...array_size"Is that pseudo-code, C++0x or a typo?
Vulcan Eager
Considering the syntax differs between the two examples, has to be pseudo-code.
MSalters
I thought pseudocode would be better as its more general, though I've changed it back to be more specific to C++
Beh Tou Cheh
+2  A: 

Overload operator<< for your class. You could do it as follows:

ostream& operator<< (ostream& os, const MyClass& mc)
{
  return os << mc.s /* << ... other members*/ << endl;
}
Kirill V. Lyadvinsky
It's a good idea to define operator>> as well.
Bill
+1  A: 

What exactly do you want to write to file? In C++, you can't make assumptions about the content of an object like you can do in C. std::string for instance typically holds pointers, allocators, string lengths and/or the first few characters. It will certainly not hold the entire char[] you'd get from string::data(). If you have a std::string[3], the three sring::data() arrays will (almost certainly) be non-contiguous, so you will need three writes - each call can only write one contiguous array.

MSalters