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:

//To read a file in text mode
std::fstream in_file {"../file.txt", std::ios::in};
 
//To read a file in binary mode
std::fstream in_file {"../file.txt", std::ios::in|std::ios::binary};

Syntax to create object of istream class:

//For reading text file
std::ifstream in_file {"../file.txt", std::ios::in};
//OR
std::ifstream in_file {"../file.txt"};

//For reading in binary mode
std::ifstream in_file {"../file.txt", std::ios::binary};

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

 std::ifstream in_file;
 std::string filename;
 cin >> filename;
    
 in_file.open(filename);
    
 //OR
    
 in_file.open(filename,std::ios::binary);

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.

if(in_file.is_open()){       //Or if(in_file)
    //read from file
} else {
    //File could not be opened
    //Does it exist?
    //Should we terminate the program
}

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:

in_file.close();

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

#include <iostream>
#include <fstream>
using namespace std;
 
int main()
{
    int roll;
    string name;
    double marks;
 
    //For reading text file
    //Creating ifstream class object
    std::ifstream in_file {"file.txt"};
    
    //check if the file is open
    if(in_file.is_open()){
        //Assuming we know what is & how it is stored in the file
        //we read the data from the file
        
        cout<<"Using extraction operator" << endl; 
        in_file >> roll;
        in_file >> name;
        in_file >> marks;
 
        cout << "Roll: "<< roll << endl; 
        cout << "name: " << name << endl;
        cout << "marks:" << marks << endl;
        
        //close file
        in_file.close();
    }
    else{
        cout << "cannot read 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

#include <iostream>
#include <fstream>
using namespace std;
 
int main()
{
    string line;
 
    //For reading text file
    //Creating ifstream class object
    std::ifstream in_file {"file.txt"};
 
    if(in_file){   // OR if(in_file.is_open())
 
        //Assuming we don't know what is stored in the file
        //Therefore we will use getline() method
 
       while(!in_file.eof()){
           getline(in_file, line);
           cout << line << endl;
       }
       
        //close file
        in_file.close();
    }
    else{
        cout << "cannot read 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

10 + 1 =