suresh
suresh

Reputation: 4244

how to make data structures persistent in c++?

how to make data structures(like trees, graphs ) persistent in c++?

Upvotes: 0

Views: 1417

Answers (3)

mentatkgs
mentatkgs

Reputation: 1601

struct S {
  /* ... */
};

//...

ofstream out("temp.aux");

S s;

char* c = reinterpret_cast<char*>(&s);
out << sizeof(s);
for(int i = 0; i < sizeof(s); ++i) {
  out << c[i];
}
out.close();

// ...

ifstream in("temp.aux");
int size;
in >> size;
char* r = new char[size];
for(int i = 0; i < size; ++i) {
  in >> r[i];
}
S* s = reinterpret_cast<S*>(r);
in.close();

quick and dirty =D

Upvotes: 1

a&#39;r
a&#39;r

Reputation: 37029

In general, you will need to serialise the structure so that you can write it to a file or a database. If you have a custom structure, then you will need to write the method to serialise and deserialise (i.e. write out and read in the structure). Otherwise, if you have used a structure from a library, there may already be (de)serialisation methods.

eg. A linked list might serialise as a string like so: [1,2,3,4,5]

Upvotes: 3

Related Questions