Last Updated: June 6, 2026
std::ofstream is the output counterpart to the std::ifstream from the previous chapter. It's a stream that sends characters to a file on disk instead of to the terminal. Once it's open, writing to it with << works the same way as writing to std::cout, and the C++ runtime takes care of buffering the data and flushing it to the file. This chapter covers how to open a file for writing, the formatted and single-character write paths, the difference between "\n" and std::endl, when to call flush(), how to detect failed writes, and the default truncating behaviour. The full set of open modes (append, binary, and others) is the subject of the next chapter.