Ifstream C++ How to open text file and read data


Ifstream C++

Ifstream stand for input file stream used to read data from file. There are simple five steps to read data from text file as below

Step 1: Include header file fstream

To use ifstream to read from file, just include fstream header file at top (like iostream) as below

#include <fstream>

Step 2: Create object of input file stream (ifstream)

Below line is used to create object of ifstream (input file stream)

ifstream ifile;

Here ifile is an object of ifstream and we can use this object to perform all input file operations.

Third Step: Open text file and read data

Using dot operator (.), we can call open() method associated with object ifile. Below line is used to do this.

ifile.open(
    "myfile.txt",
    ios::in
); 

First parameter of open method is text file name. You may provide complete address of location where file is located. 

Second parameter is file opening mode. There is only one option to open file for reading data which is 

  • ios::in         To read data from file

This is default mode to open file for reading purpose so it is optional. If you don't write ios::in then compiler include it by default.

Forth Step: Read data from file

To read complete line from file, we use a method getline(). This methods takes two parameters.

string country;
getline(ifile,country))
cout<<country;  

First Parameter is the object of ifstream which is ifile. It reads complete line from file and copy it to second parameter which is a string named country. We can display this string country. 

Fifth Step: Close the file

Don’t forget to close file at the end of program so that resources allocated to ofstream can be de-allocated by the operating system.

Below is a complete C++ program to read data from text file

ifstream C++
Ifstream C++
Output

ifstream C++ output
Ifstream C++ output

No comments:

Post a Comment