Returning failure result for operator << istream
I'm trying to read and write a class from/to disk, but altough it works, I want to implement better error checking, but not sure how to do it. I would have thought that using stream.read would cause an exception if an attempt to read past the end of the file occured, but it doesn't seem to.
At the moment, my loader code is something like this:
The above is part of FooTemplate, which is a subclassed vector template and contains additional features like customised array system with full disk I/O tailored to my app.
ifstream FooLoader (filename, ios::binary);
clear(); // empty the array
FooLoader >> p;
while (FooLoader.eof() == FALSE)
FooLoader >> p;
else return 0;
Now, my >> operator code is as follows:
istream & operator >> (istream &stream, FooClass &obj)
stream.read ((char *)&obj.Time, sizeof(obj.Time));
stream.read ((char *)&obj.ID, sizeof(obj.ID));
stream.read (&obj.BinDataSize, sizeof(obj.BinDataSize));
if (obj.BinData) free  obj.BinData;
obj.BinData = new char[obj.BinDataSize];
stream.read (obj.BinData, obj.BinDataSize);
Now, although this works, the things I don't like about this are:
Reading an extra element which could allocate upto 255 bytes for no reason. Sure, it'll get cleaned up by the destructor when "p" goes out of scope, but it's ugly and I don't like it.
Lack of error detection. How can I tell if a "stream.read" command failed? It doesn't return the number of bytes actually read, despite the compiler documentation stating it does.
Since I have to return a stream (why?), how do I return an error status from my reading function? The only way I can think of is "throw", but I don't want to have to put a "try... catch" around every place where it will call the routine.
EDIT: I fixed the ZeroMemory issue by adding a copy-constructor. Updated code is now above.