Replacing text in a file.

I'm having trouble editing text in a simple .txt file. My problem is that I don't know how to replace a string of text of a certain length without losing a character in the process. For example:

#include <fstream>
#include <iostream>

using namespace std;

//simple program to try and replace text in a file

int main(){
int g;
string t;

//opening the file stream for input and output

fstream test;
test.open ("test.txt", ios::in | ios::out);

//testing to make sure stream is still ok

if (!(test))
cout << "Error";

//verify that pointer is at beginning of file and then taking in
//and echoing first line of file

g = test.tellg ();
cout << g;
test >> t;
cout << t;

//replacing text in file

test.seekp (5, ios::beg);
test << "false";

//once again outputting first line of file

test.seekg (0);
test >> t;
cout << endl << t;


return 0;
}

Above is the code I've written, and what I'm trying to do is replace the text "true" with "false".

The text document looks like this:

open=true
closed=false

and every time I run this program I get the output:

open=falseclosed=false

I'm assuming that this is because "false" is one character longer than "true" and it replaces the return but I don't know how to make it stay in the same format after my program runs.

Any tips at all would be appreciated thanks!
easiest way would be to use tmpnam() or tmpfile() to copy up to the insertion point from the original fstream, then add any text to be inserted, then copy from the end of insertion point to the end of file.

after that, it's just a matter of copying the temporary fstream into the actual file after truncating.
Topic archived. No new replies allowed.