void update()
{
tyre rec;
char id[10];
int found=0;
cout<<"\n\t\t\t*********************************\n";
cout<<"\t\t\t\tUpdate a record."; //heading
cout<<"\n\t\t\t*********************************\n";
cout<<"\n\t\t\tEnter the ID to update record.";
cin>>id;
fstream update("tyres record.txt",ios::in|ios::out);//open file for input & output.
if(!update) cout<<"\n\t\t\tError in opening file";
else
{
cout<<"\t*****************************************************************\n";
cout<<"\tID"<<setw(20)<<"Name"<<setw(20)<<"Size"<<setw(20)<<"Price\n"; //heading of table.
cout<<"\t*****************************************************************\n";
while(!update.eof() && found==0)
{
update>>rec.id>>rec.name>>rec.size>>rec.price; //reading records.
if(stricmp(rec.id,id)==0) //matching record to update.
{
cout<<"\t"<<rec.id<<setw(20)<<rec.name<<setw(20)<<rec.size<<setw(15)<<rec.price<<endl<<endl; //print matched one.
found=1; //terminate loop if found.
}
}
}
if(found==0) //check if not found
cout<<"\t\t\tRecord not exist..\n";
else //record found.
{
cout<<"\t\t\t**********Udate Information**********\n\n"; //take new data for founded record.
cout<<"\t\t\tEnter new ID:"; cin>>rec.id;
cout<<"\n\t\t\tEnter new name:"; cin>>rec.name;
cout<<"\n\t\t\tEnter new size:"; cin>>rec.size;
cout<<"\n\t\t\tEnter new price:"; cin>>rec.price;
int pos=-1*sizeof(rec); //find the location of founded record.
update.seekp(pos,ios::cur); //set pointer to founded location.
update<<rec.id<<setw(20)<<rec.name<<setw(20)<<rec.size<<setw(15)<<rec.price<<endl; //insert new data.
cout<<"\n\t\t\tRecord updated...\n";
}
update.close(); //closing file.
cout<<"Press any key to continue";
getch();
system("cls");//clear the screen.
}//End of the function.
It work it match the record and print bt when i update using pos variable it update on wrong position on file and sometimes id is nt updates rest are updated...here is the seekp problem i think
Oh, I didn't notice first: update>>rec.id>>rec.name>>rec.size>>rec.price;
This doesn' work.
You can use update.getline(rec.id, 10, '\n'); the third argument is the delimiting character which depends on how you store each field in the file, line by line for example?
sizeof(rec) == 60, so you are always seeking 60 characters backwards. I'm not sure about your updating output, perhaps: update<<setw(10)<<rec.id<<setw(20)<<rec.name<<setw(20)<<rec.size<<setw(10)<<rec.price<<endl;