Reading from a Text File

In C++, to read from files two streams/classes are commonly used:

  • fstream
  • ifstream

First need to include fstream class into our program.

Then we create an object of any of the two class. e.g Creating object of fstream class

Or we can also use ifstream class.

The above method assumes that the file name is available prior to the creation of the file streams object. But in case the file name is not available and the user will input the file name during runtime then you can use open() method to give file name after getting input from the user. E.g

Till now we created the stream and connected it to the file. But we have to make sure it was successful before doing any operation. For this we use is_open() method.

is_open() returns boolean indicating whether the file was opened for processing or not.

Now the main task comes, how to use file stream object to read data from a file.

There are two ways:

  1. Read formatted data.
  2. Read unformatted data.

We choose first way, when we know what type of data is present in the file. To read formatted data we use extraction operator (>>). The same way we used it with cin.

File Handling in C++

And if we don’t know what type of data is present in the file, then it will be better to read line by line using getline() method.

Reading from a Text File in C++

When using geline() method we check whether the control has reached the end of the file using eof() method.

Now after doing all reading operation, we must close any open file to flush unwritten data. To close a file we use close() method on stream object.

Take a look on the “C program to read a text file” to understand the file stream object working.

C Program to Read from a Text File when Format known

Output

When file.txt is not present beside executable program file.

Reading file When file.txt is not present

Output of read file C++ program

When file.txt with the appropriate data is present.

Read file when file is present

File Stream Class in C++

C Program to Read from a Text File when Format Not known

Output

File handling in C

That’s all for reading file in C++. Before writing program make sure the file is present at the correct directory and the correct relative path is provided to file stream class object. If you have any doubt then comment below. I will surely help.

Leave a Reply

Close Menu