Home > OS >  How to save data in file I/O in c
How to save data in file I/O in c

Time:11-07

i was trying to create login and registration syste. The registration work perfectly well until i stop the app and run it again so that i can login(it delete everything in the file). How can I make my file save even when I run again my app bellow is attached my code

#include <iostream>
#include <fstream>
using namespace std;
double amount;
int main () {
ifstream fin;
ofstream fout;
fin.open("admin.txt");
fout.open("userDB.txt");

int number;
string username,password, adminUsername, adminPassword,newusername,newpassword; 
fin>>adminUsername;
fin>>adminPassword;

if(number == 1){
cout<<"Welcome to the Normal User Login Page : \n\n";
cout<<"Enter Username : ";
cin>>username;
cout<<"Enter password : ";
cin>>password;  
}
else if(number == 2) {
cout<<"Welcome to the Registration and Deposit Page\n";
cout<<"Enter administrator username and password.\n";
cout<<"Enter username : ";
cin>>username;
cout<<endl;
cout<<"Enter Password : ";
cin>>password;
if(username == adminUsername){
    if(password == adminPassword){
        cout<<"Welcome admin \n";
        cout<<"1. Deposit money for client\n";
        cout<<"2. Register new client\n";
        cout<<"3. Reset your password \n\n";
        cout<<"Enter option to proceed : ";
        cin>>number;
        if(number==2){
            cout<<"Client register form\n";
            cout<<"Enter client username : ";
            cin>>newusername;
            cout<<"Enter client password : ";
            cin>>newpassword;
            cout<<"initial deposit : ";
            cin>>amount;
            fout<<newusername<<endl;
            fout<<newpassword<<endl;
            fout<<amount<<endl;
            
        }
        
    }
    else{
        cout<<"Wrong password";
    }   
}
else{
    cout<<"Wrong UserName";
}
    
}
fin.close();
fout.close();
return 0;
}

I am new to C kindly help.

CodePudding user response:

It is because whenever the output file is opened it clears the contents of it. You need to specify the option to append to the file in order to prevent that:

fout.open("userDB.txt",std::ios_base::app);
  •  Tags:  
  • c
  • Related