← Back to Streams
Question 666
File-Backed Key-Value Store
File-Backed Key-Value Store
Build a classKVStorethat 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 ifkeyexists, 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;trueif the key existed,falseotherwise. -int count() const: the number of entries in the file. Every method reads the file fresh (ios::in, readingkey >> valuepairs until reading fails) — nothing is cached;setandremovewrite all entries back inios::out | ios::truncmode. The test starts with an empty file and prints, one per line, the results ofget((missing)for the empty string),count, andremove(true/false). Forset("color", "red"),set("size", "M"),set("color", "blue"), thenget("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
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.