I have .txt
file and there are lines:
username1:123456789:etc:etc:etc:etc
username2:1234:etc:etc:etc:etc
username3:123456:etc:etc:etc:etc
username4:1234567:etc:etc:etc:etc
username1 - username; 123456789 - password; etc - more text.
I have code to read file and find line where is username
what I need. Also code change password, but there is problem if new password is longer that old one then it looks like:
username3:11111111111tc:etc:etc:etc
if new password is shorter then it looks like:
username1:111111789:etc:etc:etc:etc
I have length of new password, but how can I get length of old one and replace it properly?
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();
}
I'm working on Linux, writing in C++.
Edit
Maybe there are way to add string in text, but not replace it and also way to erase string by not replacing it? Then I could read length of old password compare it with new password and delete/add letters in string to replace it properly.