← Back to Streams
Question 658
Persistent Counter
Persistent Counter
Write a functionint incrementCounter(const string& filename)that: 1. tries to openfilenamefor reading (ios::in) and read one integer from it; 2. if the file could be opened and an integer was read, the new value is that integer plus 1; otherwise (the file does not exist or is empty) the new value is 1; 3. opens the file inios::out | ios::truncmode, writes the new value to it, and returns the new value. The test prints each returned value on its own line. If the file contains5, one call prints the output shown in Expected Output. If the file does not exist, the first call prints1and a second call then prints2: 1 2 Do NOT write a main function.
Expected Output:
6 1 2
= newline. The output ends with a newline — print one after the last line.
Hints4 available
Sign in to use hintsTopics:
Streamsfstream
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (cout, fori)
Your Output
Run your code to see the output here...
Test Cases
Run your code to see test case results.