Inserting with the << Operator in C++

By John Paul Mueller, Jeff Cogswell

Writing to a file is easy in C++. You’re probably already familiar with how you can write to the console by using the cout object, like this:

cout << "Hey, I'm on TV!" << endl;

Well, guess what! The cout object is a file stream! Amazing! And so, if you want to write to a file, you can do it the same way you would with cout:. You just use the double-less-than symbol, called the insertion operator, like this: <<.

If you open a file for writing by using the ofstream class, you can write to it by using the insertion operator. The FileWrite01 example shown demonstrates how to perform this task.

#include <iostream>
#include <fstream>
using namespace std;
int main()
    ofstream outfile("outfile.txt");
    outfile << "Lookit me! I'm in a file!" << endl;
    int x = 200;
    outfile << x << endl;
    return 0;

The first line inside the main() creates an instance of ofstream, passing to it the name of a file called outfile.txt.

You then write to the file, first giving it the string, Lookit me! I’m in a file!, then a newline, then the integer 200, and finally a newline. And after that, show the world what a good programmer you are by closing your file.