Summary: In this tutorial, we will learn to read the file using the stream classes in C++.

Input File Stream Class

The fstream library provide the following two classes to read files in C++:

  • fstream: File stream class used both for reading and writing to a file.
  • ifstream: Input stream class used for reading data from files.

To read a file, we start by creating an object of any of these classes.

Syntax to create object of fstream class:

Syntax to create object of istream class:

If the user has to input the file name, then we can use the open() method to initialize the input file stream object:

Read Data from the File

So far we created the stream and connected it to the file. But we have to make sure that it succeeded before carrying out any operation. For this, we use the is_open() method.

The is_open() method returns true if the file is open for processing, otherwise it returns false.

Once the file is open and connected, we proceed to read its contents.

we can read data from a file in two ways:

  1. Formatted: Used when the type and structure of the data are known.
  2. Unformatted: Used when we don’t know the type or structure of the data.

Read Formatted Data

We use the extraction operator (>>) to fetch the formatted data from the file.

Here is an example, which reads integer, double and string from the file:

Reading Formatted data from file in C++

Read Unformatted Data

When we don’t know what type of data is present in the file, then we use the getline() method to read its content line by line.

Reading from file line by line in C++

In the above example, we are only reading the first and the only line of the file.

To read multiple lines, we write the getline() method inside the while loop with the condition inline.eof() != true.

The eof() method returns true, when the interpreter reaches the end of the file.

Close File After Reading

When the read operation completes, we must close the open file to flush unwritten data.

To close a file we invoke the close() method on the stream object:

C++ Example: Read Formatted Data from a Text File

Output:

When the file (file.txt) does not exist:

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++ Example: Read UnFormatted Data from a Text File

Output:

File handling in C

In this example, all the data from the file is fetched as string.

Note: Before writing the program make sure that the file exists in the correct directory and the correct relative path is provided to the file stream class object.

Leave a Reply

four × 5 =