Open In App

How to Read a File Line by Line in C++?

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

In C++, we can read the data of the file for different purposes such as processing text-based data, configuration files, or log files. In this article, we’ll learn how to read a file line by line in C++.

Read a File Line by Line in C++

We can use the std::getline() function to read the input line by line from a particular stream. We can redirect the getline() to the file stream to read the file line by line.

C++ Program to Read File Line by Line

C++




// C++ Program to Read a file line by line using getline
#include <fstream>
#include <iostream>
#include <string>
  
using namespace std;
  
int main()
{
    // Create an input file stream object named 'file' and
    // open the file "GFG.txt".
    ifstream file("GFG.txt");
  
    // String to store each line of the file.
    string line;
  
    if (file.is_open()) {
        // Read each line from the file and store it in the
        // 'line' variable.
        while (getline(file, line)) {
            cout << line << endl;
        }
  
        // Close the file stream once all lines have been
        // read.
        file.close();
    }
    else {
        // Print an error message to the standard error
        // stream if the file cannot be opened.
        cerr << "Unable to open file!" << endl;
    }
  
    return 0;
}


Input File: GFG.txt

gfg-txt-file-min

GFG.txt

Output

Screenshot-2024-02-02-230142-min


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads