Monday, November 16, 2009

Todo

The following code prints the contents of the file containing Students' records backwards (today's class todo):

#include
#include
using namespace std;
#include

class Student{
char _name[51];
int _noOfSubjects;
float _gpa;
public:
Student(const char name[]="", int noOfSub=0, float gpa=0.0){
strcpy(_name, name);
_noOfSubjects = noOfSub;
_gpa=gpa;
}
ostream& print(ostream& os)const{
return os<< "name: "<< _name<< ",Subjects: "<< _noOfSubjects<< ",Gpa: "<< _gpa;
}
};

ostream& operator<< (ostream& os,const Student& S){
return S.print(os);
}

int main(){
Student S;
fstream fin("std.bin",ios::in| ios::ate | ios::binary);
int cnt = (fin.tellg()/sizeof(Student));
for(int i=0; i< cnt; i++){
fin.seekg((-sizeof(Student))*(i+1), ios::end);
fin.read((char*)&S, sizeof(Student));
cout<< S << endl;
}
return 0;
}


Input File:
name: John Doe,Subjects: 4,Gpa: 3.5
name: Fred Soley,Subjects: 3,Gpa: 2.5
name: Fardood Solimon,Subjects: 2,Gpa: 3.5
name: Joe Black,Subjects: 5,Gpa: 3

Output:
name: Joe Black,Subjects: 5,Gpa: 3
name: Fardood Solimon,Subjects: 2,Gpa: 3.5
name: Fred Soley,Subjects: 3,Gpa: 2.5
name: John Doe,Subjects: 4,Gpa: 3.5

Tuesday, September 15, 2009