Reputation: 61
The code goes like this
ofstream f("bank.dat", ios::app);
ifstream fa("bank.dat");
int n = 0, flag = 0;
struct bac
{
char name[10];
char amt[5];
} s;
void add()
{
cout << "\nenter the details ";
cin >> s.name >> s.amt;
f.write((char *)&s, sizeof(bac));
}
void ser()
{
ifstream fa("bank.dat");
fa.seekg(0);
char x[10];
cout << "\nenter value to be searched ";
cin >> x;
while (fa && flag == 0)
{
n++;
fa.read((char *)&s, sizeof(bac));
if (strcmp(s.name, x) == 0)
{
flag = 1;
break;
}
}
if (flag == 1)
{
cout << "\nfound";
cout << "\nAmount " << s.amt;
}
}
void mod()
{
ser();
cout<<" "<<n;
if (flag == 1)
{
f.seekp((n - 1) * sizeof(bac));
// cout<<f.tellp();
cout<<"\nnew details ";
add();
}
}
int main()
{f.seekp(0);
int ch;
cout << "\nBANK MANAGEMENT SYSTEM \n";
cout << "enter choice ";
cout << "\n1.add\n2.search\n3.delete and overwrite ";
cin >> ch;
if (ch == 1)
{
add();
}
if (ch == 2)
{
ser();
}
if (ch == 3)
{
mod();
}
return 0;
}
What I am trying to do is to make a program with search , display and modify functions ;
ERROR
The record gets appended at the last , even when i use
f.seekp((n - 1) * sizeof(bac));
OPERATIONS PERFORMED
*add sid , sar named entries with amts 5,6 respectively
*replace sid named entry with name : sid (same as original ) amt :7
THE OUTPUT IN FILE
EXPECTED sid 7 sar 6
FOUND sid 5 sar 6 sid 7
Upvotes: 0
Views: 147
Reputation: 2218
I think this is because you are using ios::app flag.
As it is written here:
app: (append) Set the stream's position indicator to the end of the stream before each output operation.
Upvotes: 1
Reputation: 697
Reinitialize 'n = 0' at the beginning of ser() operation. Currently you keep increasing 'n' everytime search is called and that's the reason record gets appended to the end of file. I would advise not to use global vars 'n' and 'flag', rather return these values e.g.
int ser()
{
// return n if search succeeds else return '-1'.
}
I see it could be improved in various ways, perhaps take a look at example code on IO in standard book.
Upvotes: 1