Home > Articles > Programming > C/C++

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Writing to a File

The preceding example, Take 4, works with writing to files, too. One of the many beauties of C++ is that the cout object is simply a file stream object, and you can use the same formatting techniques to write to a file.

First, add the following include line after your iostream include line:

#include <fstream>

Now try this code at the end of your main function:

ofstream f("/myfile.txt");
f << "Take 5" << endl;
f << showpoint;
f << x << " ";
f << y << " ";
f << z << endl;
f << p << " ";
f << q << " ";
f << r << endl;
f << endl;

This is the exact same code as Take 4, except that it writes the output to a file instead of the console. Notice that I created a file stream called f. Then, instead of writing to cout, I wrote to f using the same f << x notation. That's pretty easy! And it's cool, too, because you can treat the cout and a file as the same thing. Take a look at this function:

void writestuff(ostream &o) {
  o << "a" << endl;

All this function does is write a letter a and a newline to a file. If you create a new ofstream object as in Take 5, before closing the file you can call this writestuff file as follows:


This code passes the f object to the function, and the function writes to the file. Or you can pass the cout object like so:


This tells writestuff to write the letter a to the console. That's reusability!

  • + Share This
  • 🔖 Save To Your Account