Signup/Sign In
LAST UPDATED: OCTOBER 31, 2020

C++ Reading from a file Program

Hello Everyone!

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:

Code:

 #include<iostream> #include<fstream> //to make use of system defined functions for file handling using namespace std; int main() { 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 string str; // creating a variable of type ifstream to make use of file handling commands and open a file in read mode. ifstream in; //open is a system defined method to open and read from the mentioned file in.open("studytonight.txt"); //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 while(in>>str) cout << str << " "; cout << "\n\n\n"; // close the file opened before. in.close(); return 0; }

The contents of the studytonight.txt file are:

 Studytonight: Our mission is to empower young Students to be the inventors and creators.

Output :

C++ read from a file

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 : )



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.