Problem with writing to a file.

Jan 5, 2015 at 11:01pm
I have been writing scores for a player to a text file using ofstream and it works perfectly however, everytime I run the program, it overwrites the previous data I saved.

How can I write to the file AFTER what's already in the text file, for instance.

Text file contains:

1
2
Name: Bob
Score: 500


Text file after adding new score:

1
2
3
4
5
Name: Sally
Score: 400

Name: Bob
Score: 500


Thanks for any help in advance.
Last edited on Jan 5, 2015 at 11:02pm
Jan 6, 2015 at 12:15am
Jan 6, 2015 at 12:50am
The links don't seem to work. Is there a way to do it by using the ifstream alone?
Jan 6, 2015 at 12:52am
No ifstream. Use ofstream to output anything:

1
2
std::ofstream ofs;
ofs.open ("test.txt", std::ofstream::out | std::ofstream::app);

Jan 6, 2015 at 1:01am
Oops, yes I meant ofstream sorry.

I'm still a little confused, my program writes out the data fine but I don't know how I can add more to the text file without it replacing the text already in the file.

This is my writer code that writes some data into a text file.

1
2
3
4
5
6
7
8
if (!playerName.empty())
		scoreWriter << "PlayerName: " << playerName;
	else
		scoreWriter << "PlayerName: Unknown Player";
if (correctAnswers > 1)
		scoreWriter << "\nPlayerScore: £" << moneyAmount[correctAnswers];
	else
		scoreWriter << "\nPlayerScore: Nothing";
Last edited on Jan 6, 2015 at 1:01am
Jan 6, 2015 at 1:27am
From Cplusplus.com open mode reference manual:
app		All output operations happen at the end of the file, appending to its existing contents.
Topic archived. No new replies allowed.