C/C++ Arena

Step 5 of 6

Writing files with ofstream

std::ofstream writes a file. By default it truncates (like "w" in C). Pass std::ios::app to append instead:

std::ofstream out("log.txt", std::ios::app);
out << "round " << n << "\n";

Check the stream after writing if the data matters: disks fill up. if (!out) catches failed writes as well as failed opens.

Your turn: write bool save_scores(const std::string& path, const std::map<std::string, int>& scores) that writes one name=score line per entry (the map's order), replacing any existing file. Return whether everything succeeded.

Previous: Reading files with ifstream Next: Challenge: operator>> for your own type