CJCoding With Joseph
15free / daySign inCreate account

Rotating Logger

Create a class Logger that writes log lines to a file but never lets the file grow beyond a limit.

1. Constructor Logger(const string& filename, int maxLines): stores both values. It does not create or touch the file.
2. int lineCount() const: opens the file with an ifstream and returns how many lines it currently contains (count with getline). If the file does not exist or cannot be opened, return 0.
3. void log(const string& msg): if the file already contains maxLines lines or more, open it in truncating mode; otherwise open it in append mode. Then write msg followed by a newline and close the file. Print nothing to cout.

Test 1 removes the file, creates Logger lg("rot_a.txt", 2), calls lg.log("a") and lg.log("b"), prints lg.lineCount(), then calls lg.log("c") and prints lg.lineCount() again, then reopens the file and prints every line. The output is exactly what is shown in Expected Output.

Do NOT write a main function.

Expected Output:

2
1
c
3
2
s
t

= newline. The output ends with a newline — print one after the last line.

Hints4 available
Topics:
Streamsofstream
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.