Files

Creating an Output File

Instead of showing the table in the console window, the program below writes the output to a file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream> 
#include <fstream> 
using namespace std; 
int main() { 
  ofstream inch; //output file stream 
  inch.open("c:/mycpp/inches.txt"); //associates the name inch with a file 
  if (inch.fail()) //maybe the location doesn't exist, or it is full, or protected 
    cout<<"File error\n"; //cout is used to notify user of error 
  else { //create table by writing to inch 
    inch<<"INCHES\tCM\n"; //print heading 
    for(int inches=1; inches<20; inches++) 
      inch<<inches<<"\t"<<inches*2.54<<"\n"; 
    cout<<"File created\n"; //cout is used to inform user 
    inch.close(); //close anything you open!
  } //create table 
  system("pause");
  return 0;
} //main
CODE
Compare this program to the previous one:
1
2
3
4
5
6
7
8
9
10
//Print table of inches to centimeters
#include <iostream>
using namespace std;
int main(void) {
   cout<<"INCHES\tCM\n"; //print heading
   for(int inches=1; inches<20; inches++)
     cout<<inches<<"\t"<<inches*2.54<<"\n";
   system("pause");
   return 0;
} //main
CODE

Please note the following:

  • Lines 1&2: we still need cout, but we also need fstream to output the file.
  • Line 5: we declare inch to be an outstream file.
  • Line 6: The open statement associates the c++ name inch with an external file.
  • Lines 7&8: C++ may not be able to open the requested file. There are many reasons this could happen, but we need to let the user know.
  • Lines 10, 11 and 12: These lines correspond to lines 5, 6, & 7 in the original program. Instead of writing the table to cout, we write to inch.
  • Line 13: We use cout to let the user know that the file was created.
  • External files must be closed. Closing the file will write anything that is still in the output buffer and possible other file information.

The output file will look like this: file.

NEXT: Read a list of numbers with cin