15.4. File output

Sending output to a file is similar. For example, we could modify the previous program to copy lines from one file to another.

#include <iostream>
using namespace std;

int main () {
 ifstream infile ("input-file");
 ofstream outfile ("output-file");

 if (infile.good() == false || outfile.good() == false) {
   cout << "Unable to open one of the files." << endl;
   exit (1);
 }

 while (true) {
   getline (infile, line);
   if (infile.eof()) break;
   outfile << line << endl;
 }
}

Create a code block that sends output to a file. First, make sure that both the input file and the output file are able to be opened.

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

You have attempted 1 of 4 activities on this page