Open a File for Output and Write 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>
    int main(int argc, char *argv[]) {
       fstream file1(“file1.out”,ios::app);
       ofstream file2(“file2.out”);
       ofstream file3;
       file3.open(“file3.out”);
       return 0;
    } 

    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.

    z/OS z/OS C/C++ provides overloads of the fstream and ofstream constructors and their open() functions, which allow you to specify file attributes such as lrecl and recfm.

  2. Use the output operator or ostream member functions to perform output to the file.
  3. 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.

Related Concepts

Related Tasks