File Handling through C++ Classes

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to understand File Handling through C++ classes.

The default functions used in file handling to interact with files can be defined by the user using classes. Below is the implementation of ifstream and ofstream functions.

Example

#include <iostream>
#include <fstream>
using namespace std;
int main(){
   //creating ofstream object ofstream fout;
   string line;
   fout.open("sample.txt");
   //initiating loop if file is opened
   while (fout) {
      getline(cin, line);
      if (line == "-1")
         break;
      fout << line << endl;
   }
   fout.close();
   ifstream fin;
   fin.open("sample.txt");
   while (fin) {
      getline(fin, line);
      cout << line << endl;
   }
   fin.close();
   return 0;
}
raja
Published on 23-Mar-2020 08:31:44
Advertisements