How to overwrite a specific line in a file?

I can overwrite the first line, but when it comes to the other lines, it doesn't overwrite.

I have a password.txt that has 3 passwords in it:
password0
password1
password2

and i have a user.txt that has the 3 usernames, each of them has a password. Say i want to overwrite the 2nd username which has the password "password1" instead of overwriting it, it changes only the "password0"

Here is the code for overwriting:

1
2
3
4
5
6
7
8
 string newPass;  
 char iz[100];
 ofstream newPassFile("pass.txt", ios::in);
 newPassFile.seekp(iz[100],ios::beg);
      cout<<"Enter new password for " << inUser << ": " ;
      cin>>newPass;
      newPassFile<<newPass;
      cout<<"Database updated!" << endl;


When i input a new password, it only overwrites the "password0"

Last edited on
newPassFile.seekp(iz[100],ios::beg);

I don't know what you're trying to accomplish with this line, but it isn't doing what you want.

In fact, iz[100] is an out of bounds element of your array, and therefore has potential to crash the program.



Seeking in text files generally doesn't work so hot because files are not arranged by "lines", they're arranged by "bytes". Each line has a variable width and there's no real way to know where each line stops and starts without parsing the entire file.

Furthermore, it isn't really easy to "insert" or "remove" data from the middle of a file, as it requires all the data after that point to be moved forward/back.



In this case, your best bet is to read the entire file into some kind of container that is easy to manipulate (like a vector<string>, where each element is a single line) -- then make the changes to whichever line you want in that container, then erase and rewrite the entire file with the new data.
In this case, your best bet is to read the entire file into some kind of container that is easy to manipulate (like a vector<string>, where each element is a single line) -- then make the changes to whichever line you want in that container, then erase and rewrite the entire file with the new data.

An alternative that uses less memory is to copy the source file to a destination file except that when you get to the line in question, write the new data. Once you have the destination file complete, you can delete the source file and rename the destination file to the source file's name. In the Real World you'd do it this way to guard against errors while writing the destination file and also because, if you do it just right, you can switch from the new file to the old file in an atomic operation so that any program reading the file will see the old file, or the new file, but never a file in the process of being changed and never a file that isn't there.
+1 dhayden. That is a better approach for sure.
Topic archived. No new replies allowed.