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
- First, open the file using std::
ifstream inputFile("filePath").
Then, c
heck if the file is successfully opened or not usingis_open()
that returnsfalse 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 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)
How to Read From a File in C++?
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++.