#include<iostream>
#include<fstream>
using namespace std;






// define a class to store student data
class student {
   int roll;
   char name[30];
   float marks;
public:
   student() { }
   void getData(); // get student data from user
   void displayData(); // display data
   int getNo(){return roll;}
};

void student :: getData() {
   cout << "\nEnter Roll No. : ";
   cin >> roll;
   cin.ignore(); // ignore the newline char inserted when you press enter
   cout << "Enter Name : ";
   cin.getline(name, 30);
   cout << "Enter Marks : ";
   cin >> marks;
}

void student :: displayData() {
   cout << "\nRoll No. : " << roll << endl;
   cout << "Name : " << name << endl;
   cout << "Marks : " << marks << endl;
}

int main() {
   student s[3]; // array of 3 student objects
   fstream file,file1;
   int i;
   file.open("objects.txt", ios::out | ios :: app | ios::binary); // open file for writing
      cout << "\nWriting Student information to the file :- " << endl;
     for (i = 0; i < 3; i++) {
         s[i].getData();
         // write the object to a file
         file.write((char *)&s[i], sizeof(s[i]));
      }
      file.close(); // close the file
   cout<<"Contents of file";
   file.open("objects.txt", ios :: in | ios:: binary); // open file for reading
     cout << "\nReading Student information to the file :- " << endl;
     student s1;
   while(!file.eof())
      {
      if(file.read((char *)&s1, sizeof(s1))!=NULL)
         s1.displayData();
      }
      file.close();







   //delete record

   file.open("objects.txt", ios :: in | ios:: binary);
   file1.open("objects1.txt", ios :: out | ios:: binary);// open file for reading
     // cout << "\nReading Student information from the file :- " << endl;
     // student s1;
      //for (i = 0; i < 3; i++) {
         // read an object from a file
      while(!file.eof())
      {
      if(file.read((char *)&s1, sizeof(s1))!=NULL)
          if(s1.getNo()!=4)
          {
          file1.write((char *)&s1, sizeof(s1));
          }
         //s1.displayData();
      }
   file.close();
   file1.close();
   remove("objects.txt");
   rename("objects1.txt","objects.txt");
   file.open("objects.txt", ios :: in | ios:: binary); // open file for reading
      cout << "\nReading Student information from  the file after deletion :- " << endl;
     // student s1;
      //for (i = 0; i < 3; i++) {
         // read an object from a file
      while(!file.eof())
      {
      if(file.read((char *)&s1, sizeof(s1))!=NULL)
         s1.displayData();
      }
      file.close(); // close the file

   return 0;
}

Popular posts from this blog

DDL DML DCL and TCL

Implementation of Calculator using lex and yacc

A Register Allocation algorithm that translates the given code into one with a fixed number of registers.