Writing to a file

suggest change

There 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!
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents