How to replace a part of .txt file with fstream

Hello, I tried to modify the content of .txt file using code below:

(part of function)
std::string sName,sInput;
std::vector <std::vector <int>> vnOutput (20, std::vector <int> (20))
int iPosition;
std::fstream file;
file.open("saves.txt", std::fstream::out);
...

while( file.good())
{
getline(file, sInput);
if (sInput == sName )
{
iPosition = (int) file.tellg();
iPosition -= sName.size() + 1;
file.close();
file.open("saves.txt", std::fstream::out);

if( file.good())
{
file.seekp( iPosition );
file << sName << "\n";
for( int i = 0; i < vnOutput.size(); i++)
for( int n = 0; n < vnOutput[0].size(); n++ )
file << vnOutput[i][n] << " ";
}

file << "\n";
file.close();
return;
}
}
file.close();


The saves.txt file contains blocks of data, each block has two lines:
-Name of a player (that's the sName string that we're looking for)
-400 numbers separated with space (for now they are single digits)

I want to update the second line (numbers) in one of those blocks, that's name matches with stiring sName.

The problem is that after updating one block the rest of the data is damaged (all blocks after the updated one are missing, each character before the updated block is replaced wit ^@ character).

Do you know what is the problem here or if there is an easier way to replace that data
You cannot simply insert into the middle of a text file; you could possibly overwrite a number of bytes with exactly the same number of bytes, and be careful not to break anything, but that's a heavy restriction and not worth the bother.

Create a new file, writing into it whatever you want from the old file and your new data. Delete the old file, rename the new file.
Topic archived. No new replies allowed.