How to replace a line in textfile: Please help D;

Aug 16, 2016 at 7:02pm
Im trying to make a account text file
fp>>id>>pw>>score>>unlocked;

the text file looks like this
111 123 99 2
222 222 70 2
333 321 80 2

lets say i "log" into id:222 pw:222 but i want to update the score earned and level unlocked, how can i do so?

1
2
3
4
5
6
cin<<id<<pw;
  while (!fp.eof())
{
   fp >> id >> pw >> score >> unlocked;
   if (id == inputid && pw == inputpw) cout<<"Successful login";
}
Last edited on Aug 16, 2016 at 7:23pm
Aug 18, 2016 at 1:36am
The easiest way would be to load the entire file into memory (like some sort of array of structs), change the bit of memory that you need to change, and then overwrite the file with what you have in memory.

Slightly more compilicated is to move the current location in the fstream to where you need it and then overwrite a piece of the file. To do this you need to know that the section you are overwriting already has enough space. In other words, you should not overwrite a 2 digit number with a number that has more digits. To get around this limitation you might consider using a binary file instead of a text file, but you would still need to be carefult about bit lengths. See functions like seekg, tellg, seekp, tellp, read, write, peek, and maybe a few others from http://www.cplusplus.com/reference/istream/iostream/

Another option is to use a memory mapped file, but I would recommend that you not pursue that option since you are asking this question.
Aug 18, 2016 at 3:54am
Or you could write every line to a temp file and when your done searching and changing things when you exit, ask if you want to commit your changes which writes the temp file to the source file.
Aug 18, 2016 at 6:06am
closed account (48bpfSEw)
random access file

http://www.learncpp.com/cpp-tutorial/137-random-file-io/
Aug 18, 2016 at 2:08pm
Great idea! THank you it worked!
Topic archived. No new replies allowed.