C++:Working With Files -1

A program typically involves either or both of the following kind of data communication:-

1. Data transfer between console unit and program

2. Data transfer between program and disk file.

Input Stream- supplies data to program or reads data from file.

Output Stream- recieves data from program or writes data to file.

Input operation involves the creation of an input stream and linking it with the program and input file.
Classes for FIle Stream Operations

I/O system of c++ contains a set of classes that defines the file handling methods.

These include ifstream, ofstream and fstream. These classes are derived from fstreambase class and corresponding iostream class.
Opening and Closing of File

The filename is a string of character conatining two parts - primary name and optional period with extension.
eg.  Input.data

Opening file using constructor

This method is useful when we use only one file in the stream.

1. Create a file stream object to manage    the stream using the appropriate class.
eg. class ofstream to create output stream and
ifstream to create input stream.

2. Initialize the file object with desired filename.
eg, ofstream outfile("result"); //output only
Here outfile is an ofstream object that manages the output stream.
This statement also opens the file result and attaches it to the output stream outfile.

Include the header file ifstream in program.

Opening the file using open()

This is used when we want to manages multiple files using one stream.

   file stream-class stream-object;

eg. ofstream outfile;
       outfile.close(): //Disconnect stream to data
Detecting End of File

Detecting of the end fo file condition is necessary for preventing any further attempt to read data from the file.


fin is ifstream object which returns a value of 0 if any error occurs int the file operation including end-of-file condition. Thus, the while loop terminates when fin return a value of zero on reaching the end of file condition.

Another approach to detect end-of-file condition


eof() is a member function of ios class.It returns a non-zero value if the end-of-file condition is encountered.

              < Happy Coding >


In Association with Amazon.in