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
        test.doc

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;
    stream-object.open("filename");

eg. ofstream outfile;
       outfile.open("Data");
       .....
       ....
       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.

      while(fin)

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

  if(fin1.eof()!=0){exit(1);}

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

              < Happy Coding >

Reference:
OOP by BALAGURUSWAMY

In Association with Amazon.in

Comments

Popular Posts

Top 10 Web Sites Every Programmer Should Visit Daily

C++: Huffman Coding using STL

What is "namespace" and why do we use it?