Skip to main content

Section 11.8 File Output

To write to a file, we need to create a std::ofstream object and then use its .open() method to open a file. Once that is done, we can write to the file using <<.
In this book, you will have no way to see the data in files that you write other than to try to open them and read the data. So that is what this program does. After it finishes writing some numbers to the file data.txt, it closes the file to make sure that it is available to open for reading, and then opens it with an ifstream to read the data back in:
Listing 11.8.1.
When you open a file name that does not exist, it is automatically created in the working directory. If a file with that name already exists, it is truncated on opening. That means any existing data is wiped out. If you would rather add to the existing contents of the file, you can choose to append to the file. The open command can take an optional second parameter specifying the mode to use for writing. The mode ios::app says to append new output to the end of the file instead of truncating the file:
myOutFile.open("data.txt", ios::app)

Checkpoint 11.8.1.

Checkpoint 11.8.2.

What are the contents of the output file output.txt after running the code below?
#include <iostream>
#include <fstream>
using namespace std;

int main() {
  ofstream outfile("output.txt");

  if (!outfile.good()) {
    cout << "Unable to open file" << endl;
  }

  cout << "Powers of 2: ";
  outfile << "2 4 8 16 32 64" << endl;
}
  • 2 4 8 16 32 64
  • This is the only thing we write to the output file.
  • Powers of 2: 2 4 8 16 31 64
  • Take another look at the stream objects used in the code.
  • Powers of 2:
  • This is printed to standard output, not the output file.
  • Unable to open file
  • Although this may be printed, this is not the contents of the output file.

Checkpoint 11.8.3.

Create a code block that copies all the lines from one file to another file.

Checkpoint 11.8.4.

Let’s write a program that prompts the user for a filename and opens that file. Put the necessary blocks of code in the correct order.
You have attempted of activities on this page.