Open In App

How to Read a File Using ifstream in C++?

Last Updated : 06 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, we can read the contents of the file by using the ifstream object to that file. ifstream stands for input file stream which is a class that provides the facility to create an input from to some particular file. In this article, we will learn how to read a file line by line through the ifstream class in C++.

Read File Using ifstream in C++

To read a file line by line using the ifstream class, we can use the std::getline() function. The getline() function can take input from any available stream so we can use the ifstream to the file with the getline() function.

Algorithm

  1. We will first create an ifstream object associated with the given file.
  2. We then use the getline() function and pass the previously created ifstream object to it along with the buffer.

In the following example, we will read a text file abc.txt line by line using the getline function of the input stream.

Text File abc.txt

abc.txt

C++ Program to Read File using ifstream in C++

C++




// C++ Program to Read a File Line by Line using ifstream
#include <fstream>
#include <iostream>
#include <string>
  
using namespace std;
  
int main()
{
    // Open the file "abc.txt" for reading
    ifstream inputFile("abc.txt");
  
    // Variable to store each line from the file
    string line;
  
    // Read each line from the file and print it
    while (getline(inputFile, line)) {
        // Process each line as needed
        cout << line << endl;
    }
  
    // Always close the file when done
    inputFile.close();
  
    return 0;
}


Output

output of the program

Output after reading the text file abc.txt

Time Complexity: O(N), where N is the number of characters in the file
Auxilary space: O(M), where M is the length of the longest line in the file.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads