You are on page 1of 4

Filing Example 1

============================================
#include<iostream.h>
#include<fstream.h>
#include<string.h>
#include<stdio.h>

class Student{

public: //Public
//Setter Functions
void setId(int d){

id=d;

}
void setName(char *n){
strcpy(name,n);
}
void setMarks(float m){
marks=m;
}
//Getter Functions
int getId(){
return id;
}
char *getName(){
return name;
}
float getMarks(){
return marks;
}
//Grade Function
char Grade(){
char g;
if(marks>=80)
g='A';
else if(marks>=70)
g='B';
else if(marks>=60)
g='C';
else if(marks>=50)
g='D';
else
g='F';
return g;
}

private: //Private
int id;
char name[20];
float marks;
};
void main(){ //Main
int id,ch;
char name[20];
float marks;

Student ob[5];
Student ob1;

fstream file("c:\\temp\\Std.txt",ios::in|ios::out);

cout<<"\n1-Enter data\n";
cout<<"2-Print data\n";
cout<<"3-Updata\n";
cout<<"4-Search\n";
cout<<"5-Delete\n";
cout<<"6-Sort\n";
cout<<"7-Exit";
cout<<"\n\nEnter ur choice: ";
cin>>ch;
if(ch==1){

//Write
for(int i=0;i<5;i++)
{
cout<<"\t\t\t\tSTUDENT CLASS";
cout<<"\n\t\t\t\t-------------";
cout<<"\n\nEnter Id of Student: ";
cin>>id;
ob[i].setId(id);
cout<<"\nEnter Name of Student: ";
cout.flush();
gets(name);
ob[i].setName(name);
cout<<"\nEnter Marks of Student: ";
cin>>marks;
ob[i].setMarks(marks);
file.write((char*)&ob[i],sizeof(ob[i]));
}
}
else if(ch==2){
//Read
int i=0;
while(file.read((char*)&ob[i],sizeof(ob[i]))){
cout<<"\n\n\t\t\t\tData of Student";
cout<<"\n\nID of Student : "<<ob[i].getId();
cout<<"\nName of Student : "<<ob[i].getName();
cout<<"\nMarks of Student: "<<ob[i].getMarks();
cout<<"\nGrade of Student: "<<ob[i].Grade();
i++;
}
}
else if(ch==3){

//UPDATE
int rec,s=sizeof(ob[0]);
file.seekg(0,ios::beg);
cout<<"Enter record to update: ";
cin>>rec;
rec=(rec-1)*s;
file.seekp(rec,ios::beg);
cout<<"\n\nEnter Id of Student: ";
cin>>id;
ob[0].setId(id);
cout<<"\nEnter Name of Student: ";
cout.flush();
gets(name);
ob[0].setName(name);
cout<<"\nEnter Marks of Student: ";
cin>>marks;
ob[0].setMarks(marks);
file.write((char*)&ob[0],sizeof(ob[0]));
}

else if(ch==4){

int key,count=0;
cout<<"Enter key: ";
cin>>key;
file.seekg(0,ios::end);

int fileSize=file.tellg();
int offSet=(key-1)*(sizeof(Student));

if ( offSet<fileSize){
file.seekg(0,ios::beg);
if (offSet==1)
offSet=0;
file.seekg(offSet,ios::beg);
cout<<file.tellg();
file.read((char*)&ob1,sizeof(ob1));
count=1;
}
if(count==1){
cout<<"\n\nID of Student : "<<ob1.getId();
cout<<"\nName of Student : "<<ob1.getName();
cout<<"\nMarks of Student: "<<ob1.getMarks();
cout<<"\nGrade of Student: "<<ob1.Grade();
}
else if(count==0)
cout<<"Not found";

file.close();
}

http://www.ravianeducation.blogspot.com
FARHAN: 03008855006