How to Read From a File in C++? Read Courses Practice Improve Improve Improve Like Article Like Save Article Save Report issue 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. ApproachFirst, open the file using std::ifstream inputFile("filePath").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.Read the File Line by Line using std:: getline() function and print the content.Finally, close the file using std::fstream::close().C++ Program to Read from a FileThe 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) Last Updated : 22 Feb, 2024 Like Article Save Article Previous C++ Program To Print Inverted Hollow Star Pyramid Pattern Next How to Create a Virtual Function in C++? Share your thoughts in the comments Add Your Comment Please Login to comment...