C++ Reading from a file Program
In this tutorial, we will learn how to open and read the contents of a file, in the C++ programming language.
To understand this concept from basics, we will highly recommend you to refer to this: C++ File Stream, where we have discussed this concept and the various terminologies involved in it, in detail.
The step by step commented code can be seen below:
#include<fstream> //to make use of system defined functions for file handling
using namespace std;
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to demonstrate how to read the contents from a file ===== \n\n";
//declaration of a string variable
// creating a variable of type ifstream to make use of file handling commands and open a file in read mode.
//open is a system defined method to open and read from the mentioned file
//Make sure that the file is within the same folder as that of this program otherwise, will have to provide the entire path to the file to read from
cout << "Reading content from the file and it's contents are: \n\n";
// printing the data word by word
cout << str << " ";
cout << "\n\n\n";
// close the file opened before.
The contents of the studytonight.txt file are:
Studytonight: Our mission is to empower young Students to be the inventors and creators.
We hope that this post helped you develop a better understanding of the concept of reading the contents from a file, in C++. For any query, feel free to reach out to us via the comments section down below.
Keep Learning : )