Archive

Monthly Archives: December 2013

This class takes an object and can read or write it to a position in a file.
The object must have copy constructor and operator= overloaded and ostream operator<< for printing.


#ifndef _TFILE_H_
#define _TFILE_H_
#include <fstream>

using namespace std;

template <class T>
class item{
	T data;
public:
	item(T d);
	item(char* str, int i);
	virtual ~item();
	void print(ostream &os) const;
	void read(char* str, int i = 0);
	void write(char* str,int i = -1);
};

template <class T>
item<T>::item(T d){
	data = d;
}

template <class T>
item<T>::item(char* str, int i){
	read(str, i);
}

template <class T>
item<T>::~item(){
}

template <class T>
void item<T>::print(ostream &os) const{
	os << data;
}

template <class T>
void item<T>::read(char* str, int i){
	fstream file(str, ios::in | ios::binary);
	file.seekg((ios::pos_type)(i*sizeof(data)));
	file.read((char*)&data,sizeof(data));
}

template <class T>
void item<T>::write(char* str, int i){
	fstream file;
	if (i == -1){
		file.open(str, ios::app | ios::out | ios::binary);
	}else{
		file.open(str, ios::in | ios::out | ios::binary);//ios::out call alone overwrites the entire file
	}
	if (!file){
		file.open(str, ios::out | ios::binary);
	}
	file.seekp((ios::pos_type)(i*sizeof(data)));
	file.write((const char*)&data, sizeof(data));
}

template <class T>
ostream& operator<< (ostream &os, const item<T> i){
	i.print(os);
	return os;
}


#endif