Open In App

How to Read From a File in C++?

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

In C++, file handling allows the users to read, write and update data into an external file. In this article, we will learn how to read some data from a file in C++.

Read From a File in C++

To read the content of a file in C++, we can use the std::ifstream (input file stream) to create the input stream to the file. We can then use the std::getline() function to read the data from this file and store it in into some local string object.

Approach

  1. First, open the file using std::ifstream inputFile("filePath").
  2. Then, check if the file is successfully opened or not using is_open() that returns false if file couldn’t be opened and true otherwise.
  3. Read the File Line by Line using std:: getline() function and print the content.
  4. Finally, close the file using std::fstream::close().

C++ Program to Read from a File

The below example demonstrates how we can open and read the content of a file named input.txt in C++.

C++




// C++ program to read from a file
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
  
int main()
{
    // Open the input file named "input.txt"
    ifstream inputFile("input.txt");
  
    // Check if the file is successfully opened
    if (!inputFile.is_open()) {
        cerr << "Error opening the file!" << endl;
        return 1;
    }
  
    string line; // Declare a string variable to store each
                 // line of the file
  
    // Read each line of the file and print it to the
    // standard output stream
    cout << "File Content: " << endl;
    while (getline(inputFile, line)) {
        cout << line << endl; // Print the current line
    }
  
    // Close the file
    inputFile.close();
  
    return 0;
}


Output

File Content: 
Hey Geek! Welcome to GfG. Happy Coding.

Time Complexity: O(n), where n is the number of characters to be read.
Space Complexity: O(n)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads