C++ All-in-One For Dummies, 4th Edition
Book image
Explore Book Buy On Amazon

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 
#include 
using namespace std;
int main()
{
    ofstream outfile("outfile.txt");
    outfile << "Lookit me! I'm in a file!" << endl;
    int x = 200;
    outfile << x << endl;
    outfile.close();
    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.

About This Article

This article is from the book:

About the book author:

John Paul Mueller has written more than 100 books and more than 600 articles on topics ranging from functional programming techniques to application development using C++.

This article can be found in the category: