The ofstream is a file stream class. It is used for handling files. The ofstream is used to write data to different files at different times. To use ofstream header file fstream is included.  The insertion operator used to write data to a file. In order to write to a file an object of type ofstream is created. The general form of how object is created is:


            ifstream object_name(“filename”);


The object_name is the name of the object created. The filename is the name of file to which data is to be written. The filename can contain the path where the file is stored. If no path is specified then current directory is considered. If the file does not exist then new file is created when object is created. The contents of the existing file are discarded when object is created. The file can be closed using close() function. Here is a program which illustrates the working of ofstream.




using namespace std;


int main()


            char name[50];

            int age;

            ofstream outfile("D:\\outfile1.txt");

            cout << "Enter your name" << endl;

            cin >> name;

            outfile << name << endl;

            cout << "Enter your age" << endl;

            cin >> age;

            outfile << age << endl;





The result of the program is:-


program output




The statement




includes a header file fstream in the program. The statement


            ofstream outfile("D:\\outfile1.txt");


creates an object outfile of type ofstream. The name of the file is outfile1.txt and its location is in D directory. The user enters his name and age. The statement


            outfile << name << endl;


writes the name of the user to the file. The statement


            outfile << age << endl;


writes the age of the user to the current file. 



Go to the previous lesson or proceed to the next lesson
Table of contents