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:-
The object_name is the name of the object created. The filename is the name of the file. For example,
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.
using namespace std;
cout << "While opening a file an error is encountered" << endl;
cout << "File is successfully opened" << endl;
stream1 >> a;
cout << a << endl;
The result of the program is:
includes a header file fstream for using ifstream class. The statement
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
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
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.
Go to the previous lesson or proceed to the next lesson