A small Example on
File Handling.
Example :
#include<fstream.h>
#include<string.h>
#include
<stdio.h>
class File
{
private:
char empnm[20];
float sal;
public:
void Append();
void Print();
void Modify();
void Del();
};
void File::Append()
{
File F;
fstream fptr;
fptr.open("emp.dat",ios::app);
cout<<"\n\tEnter
Employee Name : ";
cin.ignore();
cin.get(F.empnm,20);
cout<<"\n\tEnter
Employee Salary : ";
cin>>F.sal;
fptr.write((char
*)&F,sizeof(F));
fptr.close();
}
void File::Print()
{
File F;
fstream fptr;
fptr.open("emp.dat",ios::in);
while(fptr.read((char
*)&F,sizeof(F)))
{
cout<<"\n\tEmployee
Name : "<<F.empnm;
cout<<"\n\tEmployee
Salary : "<<F.sal<<"\n";
}
fptr.close();
}
void
File::Modify()
{
long
pos;
File
F;
char
name[20];
fstream
fptr;
fptr.open("emp.dat",ios::out|ios::in);
cout<<"\n\tEnter
Name to Delete : ";
cin.ignore();
cin.get(name,20);
while(fptr.read((char
*)&F,sizeof(F)))
{
if(strcmpi(name,F.empnm)==0)
{
cout<<"\n\tEnter
New Salary : ";
cin>>F.sal;
pos=fptr.tellg();
cout<<pos<<"\n";
fptr.seekg(pos-sizeof(F));
fptr.write((char
*)&F,sizeof(F));
}
}
fptr.close();
}
void
File::Del()
{
long
pos;
File
F;
char
name[20];
fstream
fptr,fptr1;
fptr.open("emp.dat",ios::in);
fptr1.open("temp.dat",ios::out);
cout<<"\n\tEnter
Name to Delete : ";
cin.ignore();
cin.get(name,20);
while(fptr.read((char
*)&F,sizeof(F)))
{ if(strcmpi(name,F.empnm)!=0)
{
fptr1.write((char *)&F,sizeof(F));
}
}
fptr.close();
fptr1.close();
remove("emp.dat");
rename("temp.dat","emp.dat");
}
int
main()
{
File
f;
int
ch=0;
while(ch!=5)
{
cout<<"\n\t1.
Append";
cout<<"\n\t2.
Print";
cout<<"\n\t3.
Modify";
cout<<"\n\t4.
Delete";
cout<<"\n\t5.
Exit";
cout<<"\n\tChoice?
";
cin>>ch;
switch(ch)
{
case
1: f.Append();break;
case
2: f.Print();break;
case
3: f.Modify();break;
case
4: f.Del();break;
case
5: break;
}
}
return
0;
}
1 comment:
File Handling in C++
File Handling concept is mainly used for store data permanently system or computer. Using file handling we can store our data in Secondary memory (Hard disk).
Post a Comment