I'm trying to make a program that uses file I/O to count the amount of times the program is used (ie the first time it is run it prints out that it was run once, the second twice, etc). My main problem is that I don't know how to clear the data in a text file at a specific point in code. This is what I typed so far:
//#include's
usingnamespace std;
int main()
{
int timesRan = 0;
ofstream fout("persistence.txt", ios::app);
ifstream fin("persistence.txt", ios::app);
read:
try
{
fin >> timesRan;
}
catch(exception e)
{
fin.open("persistence.txt");
fin.close(); // I don't know how to clear the data :/
goto read;
}
fin.open("persistence.txt");
fin.close(); // Again, I want to clear the data here.
fout << timesRan + 1;
fin.close();
fout.close();
cout << "You ran this program " << timesRan + 1 << " time(s).\n";
}
If you need any additional information please tell me. Thanks in advance.
Clearing file x of its contents requires the ios::trunc flag to be set. trunc is an abbreviation for truncate. It effectively removes the content within file x, as I've previously stated. The app flag is an abbreviation for append, which adds the output to the end of file x. Switching ios::app with ios::truc will give the desired results.