Read File Using ifstream in C++
To read a file line by line using the ifstream class, we can use the std::getline() function. The getline() function can take input from any available stream so we can use the ifstream to the file with the getline() function.
Algorithm
- We will first create an ifstream object associated with the given file.
- We then use the getline() function and pass the previously created ifstream object to it along with the buffer.
In the following example, we will read a text file abc.txt line by line using the getline function of the input stream.
C++ Program to Read File using ifstream in C++
C++
// C++ Program to Read a File Line by Line using ifstream #include <fstream> #include <iostream> #include <string> using namespace std; int main() { // Open the file "abc.txt" for reading ifstream inputFile( "abc.txt" ); // Variable to store each line from the file string line; // Read each line from the file and print it while (getline(inputFile, line)) { // Process each line as needed cout << line << endl; } // Always close the file when done inputFile.close(); return 0; } |
Output
Time Complexity: O(N), where N is the number of characters in the file
Auxilary space: O(M), where M is the length of the longest line in the file.
How to Read a File Using ifstream in C++?
In C++, we can read the contents of the file by using the ifstream object to that file. ifstream stands for input file stream which is a class that provides the facility to create an input from to some particular file. In this article, we will learn how to read a file line by line through the ifstream class in C++.