#include <iostream>
#include <fstream>
#include <string.h>
#include <ctype.h>
const int SIZE=100;
using namespace std;
class Person
{
private:
char name[30],address[50],phone[11];
public:
friend ostream &operator << (ostream &os, Person &p);
friend istream &operator >> (istream &is, Person &p);
friend ofstream &operator << (ofstream &fos, Person &p);
friend ifstream &operator >>(ifstream &ifs, Person &p);
};
ostream &operator <<(ostream &os, Person &p)
{
cout<<"_______________________________________________________________________"<<endl;
cout<<"name:"<<p.name<<endl<<"Address:"<<p.address<<endl<<"Phone:"<<p.phone<<endl;
cout<<"_______________________________________________________________________"<<endl;
return os;
}
istream &operator >>(istream &is, Person &p)
{
cout<<"Enter Full name:";
cin>>p.name;
cout<<endl<<"Enter Address:";
cin>>p.address;
cout<<endl<<"Enter Phone:";
cin>>p.phone;
return is;
}
ofstream &operator <<(ofstream &ofs, Person &p)
{
char buffer[100];
strcpy(buffer,p.name);
strcat(buffer,"|");
strcat(buffer,p.address);
strcat(buffer,"|");
strcat(buffer,p.phone);
strcat(buffer,"|");
short length=strlen(buffer);
ofs.write((char *)&length, sizeof(length));
ofs.write((char*)&buffer, length);
return ofs;
}
ifstream &operator >>(ifstream &ifs, Person &p)
{
short length;
char *name,*addr,*ph;
ifs.read((char *)&length, sizeof(length));
if (length==0)
return ifs;
char *buffer=new char(length+1);
ifs.read(buffer,length);
buffer[length]=NULL;
name=strtok(buffer,"|");
strcpy(p.name,name);
addr=strtok(NULL,"|");
strcpy(p.address,addr);
ph=strtok(NULL,"|");
strcpy(p.phone,ph);
return ifs;
}
int main()
{
Person p;
cout<<"Enter the file name:";
char filename[20];
cin>>filename;
ofstream ofile(filename,ios::binary);
char ch;
do
{
cout<<endl<<"Enter the details of the person:"<<endl;
cin>>p;
ofile<<p;
cout<<endl<<"Another?"<<endl;
cin>>ch;
}while(ch=='y');
ofile.close();
ifstream ifile(filename,ios::binary);
ifile>>p;
while(!ifile.eof())
{
cout<<p;
ifile>>p;
}
if(ifile.is_open())
ifile.close();
}
o/p
Enter the file name:test
Enter the details of the person:
Enter Full name:sri
Enter Address:India
Enter Phone:98658
Another?
n
_______________________________________________________________________
name:sri
Address:India
Phone:98658
_______________________________________________________________________
Segmentation fault (core dumped)
When I used gdb to debug this, I found out that segmentation fault is occurring while closing the file. Can anyone give me soln. Thank you in advance.