Make output file clear itself everytime program is rerun

Hi all, I am making a game where each player will pick a card and then see who wins, then this repeats for 5 rounds ... and they can choose whether to continue playing after the 5 rounds or not. I want to output the game logs into an output file where I used this method below :

1
2
3
4
5
6
7
8
9
10
  int main{
  
  do{


    recordGameLogs(); // i call my function to record game logs here

    }while(round <=5) //make the game run for 5 rounds
return 0;
}


1
2
3
4
5
6
7
8
9
10
11
void recordGameLogs()
{
	ofstream outfile;
	outfile.open("testwritezzz.txt", ios::app); // i used append mode to make sure that data is not overwritten after every round(as the game is played for at least 5 rounds)
	
	if(outfile)
	{
		outfile << "Game Log --> Round " << roundNum <<endl;
		outfile << "________________________________" << endl;
		outfile << "(all player details etc etc)"
         }


The code I sent is not complete, I just wanted to show a rough skeleton of the program. Anyways I used ::app , which is append mode to make the data be succesffuly written for all 5 rounds, if I just left it without append mode, the output file only records Round 5 details(as round 1 to 4 details are being overwritten). However, if i were to exit the program and decide to run it again , the previous game logs are still there. Is there any way for it to clear previous output content when the program is terminated, so everytime I run it only records the newest 5 rounds played .
Hello. Simply opening the file in write mode without append mode will erase the contents of the file.
If you open the file for writing with the truncate-option, you'll delete the previous content.
At these links there are some explanations :
https://stackoverflow.com/questions/17032970/clear-data-inside-text-file-in-c
https://cplusplus.com/reference/fstream/ofstream/open/
Last edited on
Hey @Geckoo, unfortunately, that is not what I need. I need to record game logs for 5 rounds, if I use truncate-option, the output only shows Logs for Round 5.
Last edited on
for it to clear previous output content when the program is terminated


Yes. The easiest is probably just to close the output file and reopen as ofstream without specifying any mode. This will create an empty file.

if you are using at least C+17, you could use std::filesystem::remove
https://en.cppreference.com/w/cpp/filesystem/remove

If you want to file to exist with no content, then you could use std::filesystem::resize with a new size of 0.
https://en.cppreference.com/w/cpp/filesystem/resize_file

Last edited on
Topic archived. No new replies allowed.