Writing to a file
suggest changeThere are several ways to write to a file. The easiest way is to use an output file stream (ofstream) together with the stream insertion operator (<<):
std::ofstream os("foo.txt");
if (os.is_open()) {
os << "Hello World!";
}
Instead of <<, you can also use the output file stream’s member function write():
std::ofstream os("foo.txt");
if (os.is_open()) {
char data[] = "Foo";
// Writes 3 characters from data -> "Foo".
os.write(data, 3);
}
After writing to a stream, check the error state. bad() reports badbit, a loss of integrity in the stream. A failed output can also set failbit; fail() is true when either failbit or badbit is set:
os << "Hello Badbit!"; // This operation might fail for any reason.
if (os.bad()) {
// Failed to write!
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents