I have .txt
文件,有几行:
username1:123456789:etc:etc:etc:etc
username2:1234:etc:etc:etc:etc
username3:123456:etc:etc:etc:etc
username4:1234567:etc:etc:etc:etc
用户名1 - 用户名;
123456789-密码;
等等 - 更多文字。
我有代码来读取文件并查找行在哪里username
我需要的。还可以通过代码更改密码,但如果新密码比旧密码长,则会出现问题:
username3:11111111111tc:etc:etc:etc
如果新密码较短,则如下所示:
username1:111111789:etc:etc:etc:etc
我有新密码的长度,但如何获取旧密码的长度并正确替换它?
My code
include<iostream>
#include<fstream>
#include <cstring>
using namespace std;
int main() {
int i=0;
bool found = false;
string line, username;
char newpass[255] = "555555555555555";
long length, plen;
cout<<"Insert username: ";
cin>>username;
username+=":";
fstream changeLINE("/.../testaDoc.txt");
if (!changeLINE) {
cout << "Can't find the file or directory!" << endl;
}
else
while (getline(changeLINE, line) && !found) {
i++;
if (line.find(username) != string::npos) {
length = changeLINE.tellg();
changeLINE.seekg((length - line.length()) + username.length() - 1);
changeLINE.write("", strlen(newpass));
cout << line << " line " << i << endl;
found = true;
}
}
if (!found)
cout << "User with username = " << username << " NOT FOUND!";
changeLINE.close();
}
我正在 Linux 上工作,用 C++ 编写。
Edit
也许有办法在文本中添加字符串,但不替换它,也有方法通过不替换它来删除字符串?然后我可以读取旧密码的长度,将其与新密码进行比较,并删除/添加字符串中的字母以正确替换它。
除非您要替换的线与新线的长度相同,否则您需要不同的策略 -
您可以使用以下策略:
- 创建临时文件
- 将您不想更改的行直接写入临时文件。您要更改的行,用新行替换
- 关闭这两个文件。
- 删除原文件
- 将临时文件重命名为原始文件名
或者您可以如评论中所述将所有行读入内存,例如行向量,替换要更改的行,然后将所有行写回到文件中,替换以前的内容。如果新行比前一行短,您可以使用以下命令截断文件:如何在使用 fstream 打开文件时截断文件
这可以工作吗:
std::vector<std::string> lines;
while (std::getline(changeLINE, line))
{
i++;
if (line.find(username) != std::string::npos) {
std::cout << line << " line " << i << std::endl;
found = true;
std::string newline = username + ":" + newpass + line.substr(line.find(":", username.length() + 2)) ;
lines.push_back(newline);
}
else
{
lines.push_back(line);
}
}
changeLINE.close();
std::ofstream ofs;
ofs.open("/.../testaDoc.txt", std::ofstream::out | std::ofstream::trunc);
for(auto& s: lines)
ofs << s << std::endl;
ofs.close();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)