使用现有文件 c++ 登录

Login with existing file c++

本文关键字:c++ 登录 文件      更新时间:2023-10-16

>我有一个基本的登录系统,它将用户输入的用户名和密码保存到文件中,用户可以通过读取文件的系统登录并检查是否存在现有的用户名和密码。但是当我关闭程序并再次运行它时,它会覆盖文件中的现有文本。我需要程序运行,其中它不会删除文件中的文本,而是继续到停止的点。另外,我不知道如何检查该文件是否已存在。

int main(){
    string username;
    string password;
    string xuser;
    string xpass;
    ifstream xFile;
    ofstream cFile;
    xFile.open("login.txt");
    cFile.open("login.txt");
    // if(there are existing username and password in the file){
    //     the file will not be overwritten and continues off to a new line
    // }
    cout<<"Register"<<endl;
    cout<<"Username: ";
    cin>>username;
    cout<<"Password: ";
    cin>>password;
    cFile << username << endl;
    cFile << password << endl;
    system("CLS");
    cout<<"Login"<<endl;
    cout<<"Username: ";
    cin>>username;
    cout<<"Password: ";
    cin>>password;
    xFile >> xuser;
    xFile >> xpass;
    if(username == xuser){
        cout<<"Username correct"<<endl;
    }
    if(password == xpass){
        cout<<"Password correct"<<endl;
    }
xFile.close();
cFile.close();
    return 0;
}

问题

使用 std::ofstream 写入文件时,默认行为是覆盖任何现有内容。

溶液

告诉std::ofstream您希望它追加到文件中,而不是在打开流时通过传递std::ofstream::app来覆盖所有内容。

替换以下行:

cFile.open("login.txt");

cFile.open("login.txt", std::fstream::out | std::fstream::app);

注意

您必须与std::fstream::app一起传递std::fstream::out。这是因为传递您自己的模式将覆盖任何默认模式,包括 std::fstream::out