/*
 * CSI2131 Winter 2005
 *
 * Assignment#2 Solution : Implementation of The DataFile class
 *
 * Shantanu Das 
 */


#include "Datafile.h"

DataFile::DataFile(fstream& fs)		//Constructor
{
	fp = &fs;						// set the file pointer
}

DataFile::~DataFile(){}				// Destructor ... nothing to be done here


void DataFile::GoToStart()
{
	fp->clear();
	fp->seekg(0,ios::beg);
}

long DataFile::appendRec(Record& rec)	// insert the record rec at the end
{
    fp->seekp(0,ios::end);			// go to the end
	long offset = fp->tellp();		//save the offset
	
	if(rec.write(*fp)==-1) {
		cerr << "Error writing record..."<<endl;
		return -1;
	}
	return offset;
}

bool DataFile::readNextRec(Record& rec)		//get the record at current position
{
	if(fp->good() && fp->peek()!=EOF){
		if(rec.read(*fp)==-1) {
			cerr << "Error reading record..."<<endl;
			return false;
		}
	}
	else return false;
	return true;
}

bool DataFile::getRec(long ofs, Record& rec)		
{									// get the record starting at byte-offset ofs

	fp->clear();					// clear the flags
	fp->seekg(ofs,ios::beg);		// seek to the begining of the record
	if(rec.read(*fp)==-1) {
			cerr << "Error reading record..."<<endl;
			return false;
	}
	return true;
}

