C++ Writing to a file


Example

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, you should always check if error state flag badbit has been set, as it indicates whether the operation failed or not. This can be done by calling the output file stream's member function bad():

os << "Hello Badbit!"; // This operation might fail for any reason.
if (os.bad())
    // Failed to write!