//================================================================== // File: rstream.c // Author: Timothy A. Budd // Platform: Cfront // Description: Template implementation of random access stream ADT // Copyright (c) 1992 by Timothy A. Budd, All Rights Reserved // Permission granted for duplication if not for profit //================================================================== // // implementation of rstream -- randomly accessed streams // # include "string.h" # include # include template rstream::rstream(const string & name) { // convert string to C style pointer variable const char * cname = name; // open the file for both input and output theStream.open(cname, ios::in | ios::out); } template int rstream::get(unsigned int index, T & value) { // first position the stream theStream.seekg(sizeof( T ) * index); // then read the value char * valuePtr = (char *) & value; theStream.read(valuePtr, sizeof( T )); // return the number of characters read return theStream.gcount(); } template void rstream::put(unsigned int index, const T & value) { // first position the stream theStream.seekg(sizeof( T ) * index); // then write the value const char * valuePtr = (const char *) & value; theStream.write(valuePtr, sizeof( T )); } template unsigned int rstream::length() { if (! theStream) return 0; else { theStream.seekg(0, ios::end); return theStream.tellg() / sizeof( T ); } } // // stream iterators // template rstreamIterator::rstreamIterator (rstream & bs) : baseStream(bs) { index = 0; } template T rstreamIterator::operator() () { T result; baseStream.get(index, result); return result; } template int rstreamIterator::init() { index = 0; return operator ! (); } template int rstreamIterator::operator ! () { T temp; // if we can read a value, we aren't at the end if (baseStream.get(index, temp) != 0) return 1; // this resets the stream pointer baseStream.get(0, temp); return 0; } template int rstreamIterator::operator ++ () { index++; return operator ! (); } template void rstreamIterator::operator = (T value) { // simply assign the value the current position baseStream.put(index, value); }