// Search structure that manages a set of PObjects
class Collection {
public:
int insert (PObject *);
int remove (PObject *);
// ...
};
// Library for reading/writing Pobjects
class IOLib {
public:
enum { MAX_CLASS_NAME = 256 };
IOLib (void) {}
int write (const char *filename);
int read (const char *filename);
void add_object (PObject*);
void remove_object (PObject*);
private:
// There a prototype for each class
Collection prototypes;
// The actual objects
Collection objects;
};
int IOLib::write (const char *filename)
{
ofstream out (filename);
if (out) {
Iterator iter (objects);
// iterate through all the objects in the objects
// collection for each one write its name and
// then use its write() method.
for (objp = iter.first (); objp != 0; objp = iter.next ()) {
out.write (objp->get_class_name (),
strlen (objp->get_class_name ()) + 1);
// write the object binary representation
// using its write () method
if (objp->write (out)==0)
return 0;
}
}
return 1;
}
// Reads a file with object returns TRUE on success
// and FALSE otherwise
int IOLib::read (const char *filename)
{
ifstream in (filename);
while (in) {
// buffer is big enough for class name.
char buf[MAX_CLASS_NAME];
// Reads class name up to terminating '\0'.
for (int i=0; in.get (buf[i]) && buf[i]; i++)
continue;
// Find a prototype and create a new instance
// (error checking is omitted).
PObject *prototype = objects.find (buf);
PObject *objp = prototype->create ();
// Read in from the file.
if (objp->read (in) == 0)
return 0;
}
return (in.eof ());
}