Home » Learn C++ » Writing Data into a File in C++

Writing Data into a File in C++

Writing Data into a File in C++:

            The insertion operator (<<) is used with “cout” object to send output to the screen. The same operator is used with the object created by ofstream (or fstream) class to send the output to the data tile on the disk. When the program ends, the object created for the file is also destroyed and the data file attached with the object is automatically closed.
For example, to write names and ages of ten persons into a data file on the disk, the program is written as:

 

Program:

 


 # include <iostream.h>
 # include <fstream.h>
 # include <conio.h>
 main ()
         {
           ofstream data(”records.dat”);
           char name [15];
           int age, i;
          i = 1;
          while (i <= 10)
                    {
                       clrscr()
                       cout<< “Enter Record #” << i << endl;
                       cout<< “Enter Name ”;
                       cm >> name;
                       cout<< “Enter Age “;
                       cm >> age;
                       data<<name<< “\t” <<age<<endl;

                       i++;
                     }
         


 

In the above program, the object “data” is created and the data file “records.dat” is attached with this object. The data is entered in the variables “name” and “age” and then it is written into the data tile through the object “data”. After writing the data into a new tile, a new line is inserted into the data tile through the “endl” manipulator.

writing-data-files

            It must be noted that the syntax of “cout” and of “data” (the object of the ofstream class) for writing data is the same.

 

Other Topics

comment closed

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
Copyright © 2010 Information Village. All rights reserved.