Read a File using C++ fstream


To create a file, use either the ifstream or fstream class, and specify the name of the file. To read to the file.

  • Include the Header file istream
  • declare a variable of type ofstream.
  • Open the file for writing.
  • check for an open file error.
  • use the file.
  • Read from the file.
  • Run the Program after each read.
  • check for end-of-file .
  • close the open file.

The C++ program demonstrates how to read a file using fstream in C++.

The program first declares a string variable myText which will be used to store the lines read from the file. Then an input file stream object MyReadFile is created with the file name "test.txt". The program then enters a while loop that reads each line of the file using the getline() function until there are no more lines to be read. Each line is stored in the myText variable and printed to the console using cout. Finally, the input file stream is closed using the close() function.

Source Code

#include<iostream>
#include<fstream>
using namespace std;
//Read a File using C++ fstream
int main()
{
    string myText;
    ifstream MyReadFile("test.txt");
    while(getline(MyReadFile,myText))
    {
          cout << myText<<endl;
    }
    MyReadFile.close();
    return 0;
}
 

Output

 On the Insert tab, the galleries include items that are
designed to coordinate with the overall look of your document.
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples