C++ 替换文件文本 - 不工作

标签 c++ fstream

我正在尝试通过搜索用户名来创建更改密码功能,如果找到确认通过,如果为 true,则将密码替换为 newPass。

文件是这样写的:USERNAME;PASSWORD

我用它来替换字符串但不确定它的语法是否正确(我是新的)

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;
}

谢谢,

最佳答案

您可以找到文件的位置,然后用完全相同字节数替换数据,但是不鼓励这样做,除非文件非常大并且发生替换对于非常少量的数据。

编辑文件内容的正确方法是:

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

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

关于C++ 替换文件文本 - 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23772639/

相关文章:

c++ - C++中的文件输入/输出

c++ - 未输入 If-block,不知道为什么

c++ - 在这个输出中 7 是正确答案而不是 6

c++ - 如何删除前导空格但保留 C++ `ifstream` 中的中间空格?

c++ - 如何返回 .dat 文件中的项目索引?

使用数组的 C++ for 循环

c++ - 宏 htonl 将内部逗号解释为参数分隔符

c++ - 将shared_ptr的 vector 复制到抽象基的派生类

c++ - 未定义的 C/C++ 符号作为运算符

c++ - 锁定时释放持有互斥锁的对象