Introduction :
In this tutorial, we will learn how to read the content of a file line by line. We will provide the file path and it will print the file content. I will show you two different ways to solve this.
Method 1: Using ifstream file stream and inputfile:
Using ifstream, we can read the content of a file, put that content in a string array and print it out. Below is the complete program :
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char strBuffer[100];
ifstream inputFile("readme.txt");
if (!inputFile)
{
cout << "File opening failed.\n";
return 1;
}
while (inputFile)
{
inputFile.getline(strBuffer, 100);
cout << strBuffer << endl;
}
inputFile.close();
return 0;
}
It will print the content of the file. Here we are using 100 as the length of the character array. If the length of one file line is more than 100, it will not print the full line. You can use any bigger size if your file line size is high.
Method 2: Using fstream and getline :
Using fstream, we can read the content of a file and read that content to a string using getline :
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream inputFile("readme.txt", fstream::in);
string str;
getline(inputFile, str, '\0');
cout << str << endl;
inputFile.close();
return 0;
}
It will print the content of the file.