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

Feedback about page:

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


File I/O:
* Writing to a file

Table Of Contents
8 Arrays
11 Loops
38 File I/O
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype