2014-05-21 54 views
1

我试图创建一个更改密码功能,通过搜索用户名,如果找到确认通过,如果是true,那么它将用newPass替换密码。C++替换文件文本 - 不工作

文件被写入像这样:用户名;密码

我用这个来代替绳子,但不知道它的语法是否正确(IM新)

tempPass.replace(0, tempPass.length(), newPass); 

这里是我当前的代码:

void AccountManager::changePassword(AccountManager & account) { 
    string username, password, newPass, passwordConf, tempUser, tempPass; 
    fstream openFile("UserPass.txt", ios_base::out | ios_base::in | ios_base::app); 

    ///Check if username exsists. 
    do { 
    cout << "Enter your username: " << endl; 
    getline(cin, username); 
    cout << "Enter you current password: " << endl; 
    getline(cin, password); 

    if (account.UserPass[username] != password) { 
     cout << "Username and password do not match. " << endl; 
    } 
    } while (account.UserPass[username] != password); 

    do { 
    cout << "Enter new password: " << endl; 
    getline(cin, newPass); 
    cout << "Retype password: " << endl; 
    getline(cin, passwordConf); 

    if (newPass != passwordConf) { 
     cout << "Password does not match confirmation. " << endl; 
    } 
    } while (newPass != passwordConf); 

    // /find/replace password with newPass in file 
    while (!openFile.eof()) { 
    getline(openFile, tempUser, ';'); 
    getline(openFile, tempPass); 

    if ((tempUser == username) && (tempPass == password)) { 
     ofstream openFile("UserPass.txt", ios_base::app); 

     tempPass.replace(0, tempPass.length(), newPass); // changes pass in file at index ;+1 
     cout << "Password has been changed. " << endl; 
     switchLog(account);         // Login on successful password change. 

     break; 
    } 
    } 
    account.UserPass[username] = newPass; 
} 

谢谢

回答

0

你可以有一个解决办法寻求到t他的位置的文件,然后用正好替换数据相同的字节量,但是这不鼓励,除非该文件是非常大的,替换发生的非常少量的数据。

正确的技术编辑文件的内容是:

  1. 读取文件的全部内容
  2. 这个修改后的数据进行读数据的修改在内存
  3. 写入新文件
  4. 删除旧文件

阅读Why is it not possible to erase contents from a file in C++?了解更多详情。

+0

可以使用ostream写入文件的任何位置。想'seekp'。 – Appleshell

+0

为了学习的目的,你能引导我在编辑方向追加我的情况吗?至于制作新文件和复制所有内容,我将如何做到这一点,而不会打破整个程序(换出名称?) – user3646473

+0

请看看编辑后的答案,并将其标记为正确,如果您认为它有帮助。 –