I am trying to find the number of times the code has been executed using the code below. But it doesn’t work.
#include <iostream>
#include <fstream>
#include <conio.h>
using namespace std;
int main()
{
fstream outputFile;
outputFile.open("count.txt");
int count;
outputFile>>count;
count = count + 1;
cout<<count;
outputFile <<count << endl;
outputFile.close();
getch();
return 0;
}
What could be the issue?
I recommend separating the concerns of (1) reading the file, (2) manipulating the data and (3) updating the file.
You should also introduce some error-handling and initialise your variables.
Here is some code to get you started:
But this is not finished. Each of the concerns I mentioned above should be extracted into separate functions.
And then you have to consider thread-safety. This would be easy enough using locking.
But what happens when you execute multiple instances of your application at the same time? You’ll need to do some file-based locking for this.
If you want to count executions on multiple machines, you have an even more interesting problem to solve.