### Opening a File for Output and Writing to the File

To open a file for output, use the following steps:

1. Declare an fstream or ofstream object to associate with the file, and open it either when the object is constructed, or later:

       #include <fstream.h>
       void main() {
          fstream file1("file1.out",ios::app);
          ofstream file2("file2.out");
          ofstream file3;
          file3.open("file3.out");
       }

   You must specify one or more open modes when you open the file, unless you declare the object as an ofstream object. The advantage of accessing an output file as an ofstream object rather than as an fstream object is that the compiler can flag input operations to that object as errors.

1. Use the output operator or ostream member functions to perform output to the file.
2. Close the file using the close() member function of fstream.

When you define an output operator for a class type, this output operator is available both to the predefined output streams and to any output streams you define.

Opening a File for Input and Reading From the File
Defining an Output Operator for a Class Type