File I/O: OUTPUT
There are six steps involved in writing information to the file (very similar
to reading information from the file):
1. Need to include an appropriate header file
2. Declare an output file stream
3. Open the file (and connect it to the declared
output stream)
4. Check whether the file opened successfully
5. Write data to the file
6. Close the file
1. To write data to an output file (use file I/O) you need to include the
library fstream in your program:
#include <fstream>
2. Declaring an output file stream object:
We read data from a file using an output file stream (or ofstream).
We must declare an output file stream object:
Syntax: ofstream OutputFileStreamName;
Examples of declaration:
ofstream outfile;
ofstream fout;
ofstream output_file;
(Think of ofstream as a new datatype. The format is the same as in declaring:
float num;)
3. Openning the file.
After declaring the output file stream object, we can open the file.
outfile.open("name of file to open");
· This links the name you
gave to the output data stream to an external file.
· Make sure you use the
name you declared ( in this case – outfile).
Examples:
a) Hard-coding the file name (name of the file is known prior to compilation).
outfile.open("result.dat"); // this opens
the file result.dat so we can write data in it.
· If a file is located in
the same directory as the source file, you just need to provide the name.
· Don’t forget to place
double quotes around the file name.
b) Sometimes you need to specify the file name at the run-time.
You need to declare a character array (we will talk about what it means later
in great detail). Then you can read the file name from the keyboard input.
ofstream outfile;
char file_name[20]; //will hold a file name of 19 characters max
cout<<”Please enter output file name:”;
cin >>file_name; // the user will provide the file name
outfile.open(file_name); //don’t need quotes around the file name in
this case.
4. Before you use the file, you should check if the file opened successfully.
Don’t ever just assume that it’s there and ready to be used.
Need to use the ‘if’ statement ( we will come back to it next week).
Example:
if (!outfile.good( ))
cout <<”File
did not open sucessfully”;
5. Writing to a file
This operation is similar to using cout.
We could output three variables to the screen using cout:
cout <<i<<j<<k;
writing data to the file has similar format:
outfile <<i<<j<<k;
6. Closing the file
Closing the file is done using close( ) function. This breaks the link between
your data file and the output file stream object. You should always do it
after you are done using the file. Do not put anything inside the parenthesis.
outfile.close( );