CJCoding With Joseph
15free / daySign inCreate account

File-Backed Key-Value Store

Build a class KVStore that keeps string keys and values in a text file: one entry per line as the key, a space, the value (e.g. color blue). Keys and values never contain spaces, keys are unique, and line order does not matter. A missing or empty file is an empty store.

Implement:
- KVStore(const string& filename): stores the filename (it need not create the file).
- void set(const string& key, const string& value): replace the value if key exists, otherwise add the entry; rewrite the file.
- string get(const string& key) const: the value, or "" if the key is absent.
- bool remove(const string& key): deletes the entry and rewrites the file; true if the key existed, false otherwise.
- int count() const: the number of entries in the file.

Every method reads the file fresh (ios::in, reading key >> value pairs until reading fails) — nothing is cached; set and remove write all entries back in ios::out | ios::trunc mode.

The test starts with an empty file and prints, one per line, the results of get ((missing) for the empty string), count, and remove (true/false). For set("color", "red"), set("size", "M"), set("color", "blue"), then get("color"), count(), remove("size"), count() it prints the output shown in Expected Output.

Do NOT write a main function.

Expected Output:

blue
2
true
1
(missing)
false
1
1

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

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