The following excerpt works to create a new object of class 'contact'. The create_contact
function works to get new data through member function getdata() and hence create a new contact and attach it to a file 'contact_diary' in a sorted manner. The display function reads that file to display the list on screen through class member function 'pudata()'. However, some junk data is getting accounted for in these create and display functions. Please suggest corrections.
void create_contact(){
contact p,q; //objects
cout<<"Enter data for new contact...";
p.getdata();
contact_diary_renew(); //this function opens and closes a file in out mode
//to refresh it's contnts
fin.open("contact_diary.txt",ios::binary|ios::in);
fin.seekg(0);
if(fin.eof()){ //when file is empty
fout.open("contact_diary.txt",ios::binary|ios::out);
fout.seekp(0);
fout.write((char*)&p,sizeof(p));
fout.close();
}
else{ //when file is not empty
int position=0,i;
fin.seekg(0);
while(!fin.eof()){ //to get location to enter new data
fin.read((char*)&q,sizeof(q));
if(strcmp(p.givename(),q.givename())<=0){
break;
}
else{
position+=1;
fin.read((char*)&q,sizeof(q));
}
}
fout.open("temp.txt",ios::binary|ios::out); //temporary file
fin.seekg(0);
fout.seekp(0);
for(i=0;i<position;i++){
fin.read((char*)&q,sizeof(q));
fout.write((char*)&q,sizeof(q));
}
fout.write((char*)&p,sizeof(p));
while(!fin.eof()){
fin.read((char*)&q,sizeof(q));
fout.write((char*)&q,sizeof(q));
}
remove("contact_diary.txt");
rename("temp.txt","contact_diary.txt");
fout.close();
}
fin.close();
cout<<"New contact created successfully!"<<endl;
getch();
}
void display_contacts(){ //function to display the list
contact p; //object
int count=0;
fin.open("contact_diary.txt",ios::binary|ios::in);
fin.seekg(0);
while(!fin.eof()){
fin.read((char*)&p,sizeof(p));
p.showdata();
count+=1;
}
if(count==0){
cout<<"List empty!"<<endl;
}
else{
cout<<"Total number of contacts: "<<count<<endl;
}
fin.close();
getch();
}