2.4.4 Writing to a File

Just like reading in from a file is similar to reading in from the console, writing to a file is similar to writing to the console. To output to a file, you will open a file as an output file stream and then stream into the file the same way you would stream to the console.

Creating the Output File Stream

As mentioned earlier in the lesson, the fstream library is used for both input and output files. To output to a file, you will first include the fstream library.

#include <fstream>

As you did with file input, you are going to create an output file stream variable and then open the file name that you want. If the file does not already exist, it will be created. If it does exist, it will be overwritten.

ofstream out;
out.open("output.txt");

Streaming To the Output File

Once the output file stream has been created, streaming to the file is the same as streaming to the console, just replacing cout with the output file stream. For example, if you use the out variable created above, you can stream Hello World to the file like this:

out << "Hello World" << endl;

When you are finished with your output, you can close the file using the close function.

out.close();

Last updated