Unique Solution for storing objects with strings in files?

I have a class Book which contains strings and integer. I tried to write the whole object to a file and read it again but it didnt work because when strings are written directly their pointer gets written and not the data.

So I tried different solutions provided on the net like reinterpret_cast or individually writing elements of object

then I came across this code:

1
2
3
4
                Book *B;
		B=(Book *)new char[sizeof(Book)];
		f1.read((char*)B,sizeof(Book));

Can someone please explain what this line means?

B=(Book *)new char[sizeof(Book)];

Thanks
Last edited on
Well, it means someone doesn't really get C++

They're allocating a char buffer which is the same size as a B struct and casting it to a Book*. (They're then reading that number of bytes into the struct, by casting it back to a char* as required by istream::read).

This should be

1
2
3
4
5
6
7
                Book *B;
		B=new Book; // allocates a B struct (which is the right size!)
		f1.read((char*)B,sizeof(Book));

		// do stuff with B

		delete B; // free memory 


You could do this, though it's a bit strange for a single struct (allocating a char buffer and reading the whole file in one go and then walking through the records is more common.)

1
2
3
4
5
6
7
8
9
10
                char *buff;
		buff=new char[sizeof(Book)];
		f1.read(buff,sizeof(Book));

		Book *B;
		B=(Book *)buff;

		// do stuff with B

		delete [] buff; // free memory 


Note that there are better solutions, esp, if B is a small struct.

If you just needed to read data into the struct in passing it would be better to avoid dynamic allocation, e.g.

1
2
3
4
5
6
                Book b;
		f1.read((char*)&b,sizeof(Book));

		// do stuff with b

		// no need to delete! 



Andy
Last edited on
PS Regarding

So I tried different solutions provided on the net like reinterpret_cast or individually writing elements of object

The latter approach is what you need when you have dynamically allocated members of a class. It's called serialization. Boost even provides a library to assist with this.

Boost Serialization
http://www.boost.org/doc/libs/1_58_0/libs/serialization/doc/index.html

Though for a simple case it would be easy enough to roll your own (pref. a string based solution, as easier to debug, etc)

Andy
Last edited on
Topic archived. No new replies allowed.