The following is my function in C++ for modifying records of bank a/c holders (A/C no and Name) in a file.
class AccountHolder
{
int accno; //Account No
char name[50]; //AC Holder name
public:
void getRecord_KB()
{
cout<<"\nEnter account no:";
cin>>accno;
cout<<"Enter name of the new account holder:";
cin>>name;
}
void showRecord_VDU()
{
cout<<"\nAccount no:"<<accno;
cout<<"\nA/C Holder's Name:"<<name;
}
int retAccno()
{
return accno;
}
};
void writeRecord_File() //Initial and subsequent writings are done through this function
{
ofstream outFile;
outFile.open("C:/PN/account.dat", ios::binary | ios::app);
AccountHolder ah;
ah.getRecord_KB();
outFile.write(reinterpret_cast<char*>(&ah), sizeof(ah));
outFile.close();
}
void modify_record(int n)
{
fstream file;
file.open("C:/PN/account.dat",ios::in | ios::out);
AccountHolder ah;
file.clear();
file.seekp(0,ios::beg);
int object_start = file.tellp();
while(file.read(reinterpret_cast<char*>(&ah), sizeof(ah)))
{
if(ah.retAccno()==n)
{
cout<<"\nEnter the new details of a/c holder:";
ah.getRecord_KB();
file.seekp(object_start);// <-- go back to position where object start.
file.write(reinterpret_cast<char*>(&ah), sizeof(ah));
}
object_start = file.tellp(); // <-- again save position where object start.
}
file.close();
}
The function modify_record(int) when called, asks for the a/c no and modifies the record with new inputs. But it also does an unwanted modification of the a/c no of the next record and the program is terminating. What am I doing wrong? I googled this type of cases and found the following two codes:
int pos = -1 * sizeof(ah);
file.seekp(pos, ios::cur);
and
long pos = file.tellp();
file.seekp (pos-sizeof(ah));
But the same problem is occurring when implemented. The rest of the program is working properly. Any suggestion? Thanks in advance.