Saturday, 2 February 2013

ifstream


The ifstream is a file stream class used for file handling. To use ifstream header file fstream is used. It is used for reading input from the file. In order to read from a file an object of type ifstream 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 the file. For example,

            ifstream  userstream(“file1.txt”);

The userstream is the name of the object and file1.txt is the name of the file. When the object is created file is automatically open. There is no need of explicitly opening the file. An error might occur while opening the file such as the file may not be found. The status of the file can be checked using ‘!’ operator along with ifstream object or using is_open() which returns true if file is open. The data can be read from the file using the insertion operator ‘>>’. The end of file can be checked using eof() function. It returns true when end of file is encountered. Here is a program which illustrates the working of ifstream.

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
            ifstream stream1("D:\\file1.txt");
            char a[80];
            if(!stream1)
            {
                        cout << "While opening a file an error is encountered" << endl;
            }
            else
            {
                        cout << "File is successfully opened" << endl;
            }
            while(!stream1.eof())
            {
                        stream1 >> a;
                        cout << a << endl;
            }
            return(0);
}

The result of the program is:

program output

The statement

            #include<fstream>

includes a header file fstream for using ifstream class. The statement

            ifstream stream1("D:\\file1.txt");

creates an object stream1 of type ifstream. The file is file1.txt which is located in D directory. During the creating of this object file is open. The statement
           
            if(!stream1)

checks whether an error is encountered while opening a file. If a file is successfully open then it returns true and prints the message “File is successfully opened”. The statement

             while(!stream1.eof())

checks the whether the end of file is encountered. The while loop is terminated when end of file comes. The statement

            stream1 >> a;

uses an insertion operator to read text from file stream. The string a will contain the text. 

No comments:

Post a Comment