How to Read From a File in C++?
Last Updated :
22 Feb, 2024
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
- First, open the file using std::
ifstream inputFile("filePath").
Then, c
heck 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 File
The below example demonstrates how we can open and read the content of a file named input.txt in C++.
C++
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ifstream inputFile( "input.txt" );
if (!inputFile.is_open()) {
cerr << "Error opening the file!" << endl;
return 1;
}
string line;
cout << "File Content: " << endl;
while (getline(inputFile, line)) {
cout << line << endl;
}
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)
Share your thoughts in the comments
Please Login to comment...