CKTIS / C++
std::ofstream — writing to a file
std::ofstream from <fstream> writes data to a file through a stream interface. Learn about default content replacement, appending, and checking errors when opening, writing, and closing a file.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <fstream>
std::ofstream out("file.txt");
out << "text\n";
out.close();std::ofstream from <fstream> is an alias for std::basic_ofstream<char>. It provides an output stream associated with a file; operator << performs formatted output. The object can be moved but not copied.
A constructor taking a path immediately attempts to open the file. The default std::ios::out creates the file if possible or discards an existing file's contents. std::ios::trunc expresses that discard explicitly. To append, use std::ios::app, which directs every write to the end of the file. std::ios::ate positions at the end only after opening; it is not a substitute for appending. std::ios::binary selects binary mode but does not turn << into a raw write of an object's representation.
Check the state with if (!out) after opening and after writing and closing. is_open() reports association with an open file, not whether all writes succeeded. By default, stream errors are reported through state flags; exceptions can be enabled with exceptions(). Output is buffered: an error may become visible only when flushing the buffer or calling close().
Object destruction automatically closes the file through its buffer. Explicit close() lets you check for a closing error before the stream ceases to exist. The example overwrites cktis-ofstream-example.txt in the current working directory and prints saved only after checking the state following closure. It uses facilities available in C++23; the linked document is an evolving standard draft, not a frozen C++23 edition.
Examples
#include <fstream>
#include <iostream>
int main() {
std::ofstream out("cktis-ofstream-example.txt",
std::ios::out | std::ios::trunc);
if (!out) {
std::cerr << "open failed\n";
return 1;
}
out << "Hello, file!\n";
out.close();
if (!out) {
std::cerr << "write or close failed\n";
return 1;
}
std::cout << "saved\n";
}
Result
saved
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.