I don't see why the file should come out empty. I get:
D:\prog\foo>type Accounts.txt
1 1234 12.34 One Eleven
2 2341 23.41 Two Twelve
3 3412 34.12 Three Thirteen
4 4123 41.23 Four Fourteen
D:\prog\foo>a
Accno> 2
PIN> 7
Amount> 76.54
Fname> Seven
Lname> Twelves
D:\prog\foo>type Accounts.txt
1 1234 12.34 One Eleven
3 3412 34.12 Three Thirteen
4 4123 41.23 Four Fourteen
4 Fourteen Fourteen Fourteen Fourteen
2 7 76.54 Seven Twelves
D:\prog\foo>
|
There are a number of serious flaws, though... (sorry).
1) Don't loop on EOF.
That's where the list of fourteens is coming from. Your loop would work better to fail after trying to read an Accno:
8 9 10
|
while (mainfile >> temp) {
if (temp != Accno) {
...
|
You actually get it right on line 49: Attempt to read, break from loop if failed to read. (This is why you don't see more duplication madness.)
2) Global variables
Accno, PIN, etc, are all global variables. Shouldn't you have those in a
struct somewhere? One you can pass as argument to your function?
3) Non-descriptive or misleading names
The
write() function doesn't just write stuff.
There is no obvious difference between
mainfile and
tempfile (though "tempfile" is an okay name).
4) Don't re-use streams.
It works okay here, but it'll bite you at some point.
5) Structural problem
This carries from the previous points.
You would do better to load the entire file into memory (into an array or a deque or something), modify it there, then rewrite the file. That's two or three functions each.
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
|
struct account {
int Accno;
int PIN;
...
};
void load( string filename, vector<account>& accounts ) {
ifstream f( filename.c_str() );
account acct;
while (f >> acct.Accno) {
f >> acct.PIN;
...
accounts.push_back( acct );
}
}
void save( string filename, vector <account>& accounts ) {
ofstream f( filename.c_str() );
...
}
int main()
{
vector<account> accts;
load( "Accounts.txt", accts );
account acct = get_account_information_from_user();
int accno = -1;
// find the account to change, if any
for (int x = 0; x < accts.size(); x++)
if (accts[ x ].Accno == acct.Accno)
{
accno = x;
break;
}
// add the new account or change the existing account
if (accno < 0)
{
accts.push_back( acct );
}
else
{
accts[ accno ] = acct;
}
save( "Accounts.txt", accts );
}
|
Hope this helps.