Rewrite an existing line in txt

Yes it's me again struggling with file, this time I want to store a changing data (victory time) of an account in file txt, and I don't know how to overwrite the old data with a new one, what I mean is replace the old number with new one, I try to code but it's getting bug and delete other account

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  fstream file("accountdata.txt");
					bool a = false;
				    
				    if (file)
					    for (int n = 1; n <= 51; n++)	
						{	
					    	file >> line;	    		
							for (int n = 0; n <= 50; n++)	
								if (line[n] == player[i].name[n])
								{
									a = true;					
								}	
								else break;
											
							if (a)
							{								
								player[i].victotal++;
								file << "\n" << player[i].victotal;
								file.close();
								break;						
							}		    													
						}


What save file look like before

duy [account name]
123 [password]
13 [old victory time]
an
1234
hai
qwe
0
yoho
zxc
1

What I want it to look like after
duy [account name]
123 [password]
14 [new victory time]
an
1234
hai
qwe
0
yoho
zxc
1
It is difficult to modify in-situ data in files. And then only when the new data is the of the same no of chars as that being replaced. If the size of the new data is not the same size of the old data then you need to start shuffling the data in the file - which is messy, error prone and probably slow and not recommended. If you want to try this, note that a file has two pointers - one for get and one for put. If you read data, this will read from the get pointer and update the get pointer but won't change the put pointer. Similarly, writing will write at the put pointer and update the put pointer but won't change the get pointer.

In situations like this, by far the best method is to read the whole file into a container (eg std::vector) of an appropriate structure, change the data as needed in the container and then write the whole container back to the file.
> note that a file has two pointers - one for get and one for put. If you read data, this will read
> from the get pointer and update the get pointer but won't change the put pointer. Similarly,
> writing will write at the put pointer and update the put pointer but won't change the get pointer.

No, not for streams associated with file buffers.

The restrictions on reading and writing a sequence controlled by an object of class basic_­filebuf<charT, traits> are the same as for reading and writing with the C standard library FILEs.

In particular:
...
--- A joint file position is maintained for both the input sequence and the output sequence.
https://eel.is/c++draft/filebuf#general-3.3
Topic archived. No new replies allowed.