Amount of times a program is used?

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//#include's

using namespace 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.
Last edited on
closed account (zb0S216C)
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.

Here's an example program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <fstream>

int main( )
{
    // Get the current count.
    int Count( 0 );
    {
        std::ifstream IStream( "Count.txt" );

        IStream >> Count;

        IStream.close( );
    }

    // Increase the count (for this execution). 
    Count++;
   
    std::ofstream OStream( "Count.txt", std::ios::trunc );

    OStream << Count;

    OStream.close( );

    return 0;
}


Wazzak
Last edited on
Thanks a lot! The program runs perfectly now.
Topic archived. No new replies allowed.