Modify data in file

Hello!
I'm trying to make simple bank database, witch is based of structure. I'm having problem with function for changing balance of specific account. Program should get positive or negative number and change balance by that number. The problem is that the new changed balance doesn't go in file, so changes doesn't save and later when I ask program to output data of client it shows the balance I had in beginning, not updated balance.
What should I change in the code for program to work the right way?
All help is appreciated.
PS: sorry for language errors, English is not my first language.

1
2
3
4
5
6
7
struct clientData
{
   int accNum;
   char Sur[15];
   char Name[10];
   float balance;
};


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  void balance change()
{
	fstream f;
	clientData a;
	int z;
	int sk;
	int atrasts;
	cout << "Enter account number of client whose balance you want to change: ";
	cin >> z;
   	f.open("test.dat", ios::in | ios::binary | ios::out);  
   	f.seekg((z-1)*sizeof(a), ios::beg);
   	f.read((char*)&a, sizeof(clientData));
   	while(f)
   	{      
   	    if(a.accNum == z)
   	    {
   	    	atrasts = 1;
			f.read((char*)&a, sizeof(a));
			cout << "Enter change in balance: ";
   	    	cin >> sk;
			a.balance = a.balance + sk;
			f << a.balance;
			f.seekg(sizeof(a), ios::cur);
			f.write((char*)&a, sizeof(clientData));
		   	cout << "Balance is changed. At the moment balance is: " << a.balance << endl;
		   	break;
		}
		f.read((char*)&a, sizeof(clientData));
   	}
   	if(atrasts != 1)
		cout << "Client not found." << endl;
   	f.close();
}
On line 23 you call seekg(), which moves the stream's read file pointer. You need to call seekp(), which moves the write file pointer. I'd also recommend moving it from std::ios::beg, rather than std::ios::cur.
Last edited on
Topic archived. No new replies allowed.