10.3 Writing, Appending, and Resource Management
Writing files is not just "put text somewhere." You need to decide whether to create a new file, overwrite old content, append to the end, create missing folders, and close resources reliably.
Writing Small Text Files
For short text, std::ofstream is the simplest option.
#include <fstream>
int main() {
std::ofstream output("study_log.txt");
output << "Today I learned std::filesystem::path.\n";
output << "std::ofstream writes text.\n";
output << "UTF-8 keeps text predictable.\n";
return 0;
}By default, std::ofstream output("study_log.txt"); creates the file if needed and replaces the content if the file already exists. That replacement behavior is useful when you are producing a fresh report, but dangerous if you meant to preserve old data.
Appending with open modes
Open modes let you say what should happen when writing.
#include <fstream>
int main() {
std::ofstream log("events.log", std::ios::app);
log << "Program started\n";
return 0;
}Common modes:
std::ios::out: open for output.std::ios::trunc: clear old content before writing.std::ios::app: write new content at the end.
Modes matter because file output can destroy data. Always make the overwrite-or-append decision visible in your code.
Buffering, flushing, and RAII
For many small writes, std::ofstream is efficient and explicit.
std::ofstream writer("scores.csv");
writer << "Name,Score\n";
writer << "Alice,92\n";Streams usually buffer data before sending it to disk. Closing the stream flushes remaining data. C++ handles this through RAII: when the stream object goes out of scope, its destructor closes the file.
You can also flush manually when you need to force buffered output out before the stream closes:
writer << "important line\n";
writer.flush();The clean habit is to keep file streams in the smallest scope that needs them. When the scope ends, the stream closes reliably.