Opening Files using Constructor

While using constructor for opening files,filename is used to initialize the file stream
object.

 

This involves the following steps

  • Create a file stream object to manage the stream using the appropriate class
    i.e the class ofstream is used to create the output stream and the class ifstream to
    create the input stream.
  • Initialize the file object using desired file name.
    For example, the following statement opens a file named “results” for
    output:

 

ofstream outfile(“results”); //output only
This create outfile as an ofstream object that manages the output stream. Similarly ,the
following statement declares infile as an ifstream object and attaches it to the file data
for reading (input).

 

ifstream infile (“data”); //input only
The same file name can be used for both reading and writing data.For example

Program1
…………………..
……………….
ofstream outfile (“salary”); //creates outfile and connects salary to it
………………
…………………..
Program 2
………………
……………
ifstream infile (“salary”); //creates infile and connects salary to it
………………..
………………….

 

The connection with a file is closed automatically when the stream object expires i.e
when a program terminates.In the above statement ,when the program 1 is terminated,the
salary file is disconnected from the outfile stream.The same thing happens when program 2 terminates.

 

Instead of using two programs,one for writing data and another for reading data ,a single
program can be used to do both operations on a file.
…………
…………….

outfile.close(); //disconnect salary from outfile and connect to infile
ifstream infile (“salary”);
………….
……………
infile.close();

 

The following program uses a single file for both reading and writing the data .First it take data from the keyboard and writes it to file.After the writing is completed the file is closed.The program again opens the same file read the information already written to it and displays the same on the screen.

 

WORKING WITH SINGLE FILE

 

//Creating files with constructor function
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<fstream.h>
int main()
{
 ofstream outf(“ITEM”);
 cout &lt;&lt;”enter item name: “; char name[30]; cin &gt;&gt;name;
 outf &lt;&gt;cost;
outf &lt;&gt;name;
inf &gt;&gt;cost;
cout &lt;&lt;”\n”;
cout &lt;&lt;”item name : “ &lt;&lt; name &lt;&lt;”\n”;
cout &lt;&lt;”item cost: “ &lt;&lt; cost &lt;&lt;”\n”;
inf.close();
return 0;
}

 

Try Now – PROGRAMMING IN C++ MCQs