Overwriting a specific entry in a file

I need some help overwriting a balance amount in two files, currently all I have it do is find the entry in the one file, read in all the information, and than add the deposit amount to it, but I can't overwrite the amount pulled from the file.

here is my code:
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
void Saving::transferFromChecking()
{
	system("cls");
	string name;
	int i = 0;
	cin.clear();
	fstream saveFile("saving.dat", ios::in | ios::binary | ios::beg);
	fstream checkFile("checking.dat", ios::in | ios::out | ios::beg);

	cout << "\t\t-=[ Funds Transfer ]=-" << endl;
	cout << "\t\t-=[ Savings to Checking ]=-" << endl;

	cout << "Account Name: ";
	cin.sync();
	getline(cin, name);
	getline(saveFile, acctName);
	
	while(name != acctName && !saveFile.fail())
	{
		i++;
		getline(saveFile, acctName);
	}

	if(name == acctName)
	 {
		 cout << "Amount to transfer: $";
		 float depAmt = 0;
		 cin >> depAmt;

		 for(int j = 0; j < 13; j++)
		{
		     char input_number; 
			stringstream converter;
			saveFile.get(input_number);
			converter << input_number;
			converter >> acctNumber[j];
		}

		 saveFile >> acctBalance;
		 if(acctBalance <= 0)
			 fatal("[!!] Insufficient Funds");
		 acctBalance += depAmt;
		 saveFile << acctBalance;
		 cout << "New Balance in Savings: $" << acctBalance << endl;
	}
	else 
		fatal("[!!] Account not found");

	saveFile.close();
	checkFile.close();
}


To clear any confusion:

Checking Balance: 500
saving balance: 200
transfer 200 from checking to savings
new checking balance: 300
new saving balance: 400


Any help would be greatly appreciated. =) Thanks in advance for your time.
Last edited on
The file is not a fixed-format file (meaning that each field may vary in size), so you really have no choice but to read the entire file, make your changes, and then write the entire file back out again. I'm not sure why you are opening the files as 'binary'.

Lines 31 through 36 don't do what you think they are doing. To convert a number from string:
1
2
3
4
5
6
7
8
9
10
11
12
// string2int()
// Converts a string of the form "123" or "-123" to its integer representation.
// Throws an int on failure.
//
int string2int( const std::string& s )
  {
  int result;
  std::istringstream ss( s );
  ss >> result;
  if (ss.eof()) return result;
  throw 1;
  }
Remember, a single char is not the same as a "character string", like char input_number[ 22 ];. In any case, you should avoid char[] arrays and use std::string instead: it makes your program more robust.

Hope this helps.
Topic archived. No new replies allowed.