File Handling Through C++ Classes



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

What's File Handling?

File handling is an important concept in programming, which allows a program to read from and write to files. C++ has built-in classes and functions for file handling, which is done using file stream classes that are part of the <fstream> library. The most common file stream classes in C++ are ofstream, ifstream, fstream.

  1. ofstream: This class is used for output file streams, where it allows the user to write data to files.
  2. ifstream: This class is used for input file streams, where it allows users to read data from files.
  3. fstream: This class combines both input and output file stream capabilities, Where which allows users to read from and write to the same file.

Example

Here is the following implementation of ifstream and ofstream functions.

#include <iostream>
#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;
}
Updated on: 2024-12-11T19:20:31+05:30

991 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements