File Handling examples in C++

Here we will discuss about the following task. This is necessary to create a project in C ++.


Let’s start Here,

The program has been expend (extra code of line) so that it is easily understood. Each option is placed in different blocks to make the program readable. To get better output of the program, execute Turbo on C++.

It has the Selection menu as follows-

If you want, you can improve it further by adding other options like Backup database, format database, recover database, user login etc. This will clear your file handling and concept as well as improve your programming skill. which is better than clearing the concept.

This block is of header files, by making comments in it, we have told their pre-defined function.

// header file include 
#include<iostream.h> 
#include<stdio.h> rename and remove 
#include<stdlib.h> // exit() 
#include<iomanip.h> // setw() 
#include<fstream> // file handling //data member and member function declaration

creating a class name is student

A class in the program, whose name is student, has been declared. In this class in public, several user defined functions have been declared. Also the constructor has also been declare-

class student
{
int roll;char sname[29];
char fname[20],mname[20];

public:
// function declaration in public mode
   student(void);   // constructor declaration for intro wizard
   ~student(void){  } // destroy object initialized by constructor
   void input_record(void);    // write record into file
   void putdata_record(void);  // display all record
   void putdata_form(void);   // create a template to displaying record on monitor
   void search_record();     // search a specific record
   void total();          // properties of program
   void modify_form(void);   // create a template to modifying record
   void modify_record();     // modify record into file
   void delete_record();     // delete spacific record

}obj;  // constructor called automatically

This is the introduction of the program which is displayed at the beginning of the program. The system (pause) function holds the screen.

student::student(void)
{ 
  clrscr();
  cout<<"/t/t/tThis program clear some concept of file handling/n";
  cout<<"/t/t";
  system("pause");
}

To insert record in the file

input_record() function used to write a file which will be call by other way,

A file has been created with the database name in the program. With function input_record () we write the data in this file. Note that here we have used the method of writing the data, the data in the file will be stored in binary format –

//get record by end user
void student::input_record(void)
{
  ofstream fout;
  cout<<"INSERT RECORD/n";

  fout.open("database",ios::app|ios::binary);
  cout<<"Enter roll no: "; 
  cin>>roll;
  cout<<"Enter stuname: ";
  gets(sname);
  cout<<"Enter father name: ";
  gets(fname);
  cout<<"Enter mother name: ";
  gets(mname);

  fout.seekp(0,ios::beg); //go to start
  fout.write((char*)&obj,sizeof(obj));
  fout.close();

  cout<<"/n/n/tRecord saved successfully...";

 create a form for display records into monitor screen

putdata_form()  function used to display  the records in a way remember here, it will not fetch the records from the file it will only display them.

void student::putdata_form(void)
 {
    cout<<roll<<"/t"<<sname<<"/t"<<fname<<"/t"<<mname<<endl;
 }

To display record from in the file

putdata_record() function will fetch the saved record from the file and  call the other function putdata_form() who will display them on monitor screen.

//display all record into monitor screen
void student::putdata_record(void)
{
  ifstream fin;
  cout<<"SHOW ALL RECORD/n";

  fin.open("database",ios::app|ios::binary);
  fin.seekg(0,ios::beg); //goto begining or start

  while(fin.read((char*)&obj,sizeof(student)))
  {
     putdata_form();
  }
  fin.close();

  //hold screen
}

If you do not want to declare two functions here, you can display and access data from only one function, but doing so can reduce the readability of this function. Hence it is divided into two parts / function here.

To Delete Record From a file 

rename and remove function, both are defined in stdio.h header file.

for rename file

rename (old-file-name, new-file-name);

for remove file

remove (filename);

for more  filename by user, remove a file, rename a file

when performing a task on a specific students then we need to access that specific record and for this we need the unique id of that record. Here the unique id will be student’s roll-no.

void student::delete_record()
{
  int x,true=0;
  ofstream fout;
  ifstream fin;
  cout<<"DETELE RECORD/n";

  cout<<"Enter student roll no: "; 
  cin>>x;

  int r = x;
  fin.open("database",ios::binary);
  fout.open("temp",ios::binary);

  while(fin.read((char*)&obj,sizeof(obj)))
  {
    if(x==r) // accessing record using their roll no
    {
      if(x!=roll) // which record not matched write into temp file
      {
        fout.write((char*)&obj,sizeof(student));
        true=1;
      }
   }
 }
 fout.close();
 fin.close();

remove("database"); //remove file
rename("temp","database"); //rename file

if(true)
   cout<<"record deleted...";
if(true!=1)
   cout<<"record not found.....";
}
if(x!=roll)

That is, we write all the other records (temp) except one record (which we want to delete) and delete this old file (database) and this new file (temp) Let’s rename it.

In search operation too, any specific record will be accessed from roll no.

To search a  specific record in the file

Here we will search student record using their roll no as a unique id

void student::search_record()
{
  int x;
  ifstream fin;
  cout<<"SEARCH RECORD/n";
  cout<<"Enter student roll no: "; 
  cin>>x;

  fin.open("database",ios::app|ios::binary);
  while(fin.read((char*)&obj,sizeof(obj)))
  { 
    if(x==roll) // if record found display
    {
       putdata_form();
    }
  }
  fin.close();
}

If record file is available, then by putdata_form () we display that record on screen.

create a form to modify old record

modify_form() displays the modified data

void student::modify_form(void)
{
  cout<<"Enter new roll no: "; 
  cin>>roll;
  cout<<"Enter new stuname: ";
  gets(sname);
  cout<<"Enter new father name: ";
  gets(fname);
  cout<<"Enter new mother name: ";
  gets(mname);

  cout<<"/n/ntRecord updated successfully...";
}

To modify a specific record in the file

Here is the syntax to modify a record.

int variable=(object-1)*sizeof(class-name/class-object);

We access the record to be modified from its roll -no and display it with putdata_form ().

// modify specific student record using their roll no
void student::modify_record()
{

  int x; char true=0;
  fstream file;
  cout<<"MODIFY RECORD/n" ;
  cout<<"Enter roll no: "; 
  cin>>x;

  file.open("database",ios::in|ios::out|ios::binary);
  while(file.read((char*)&obj,sizeof(student)))
   {
     if(x==roll)
      {
        cout<<"/nOld record are n";
        putdata_form();
        cout<<"/n/nEnter new record/n/n";

        modify_form();

        int loc=(-1)*sizeof(obj);
        file.seekp(loc,ios::cur); // give current found location into file
        file.write((char*)&obj,sizeof(student));
        true=1;
      }
   }
 file.close();
 
 if(!true) //true!=1
    cout<<"record not found.....";

}

To calculate Total record in the file

There are some manipulators in file handling which are used for many different tasks, an example of which is given below. From which we find out how much record is there in a file or how much is the size of the file. It shows the property of the file in a way. Therefore, it has been used as a separate option.

// show properties of program like total record and size of file
void student::total()
 {
   cout<<"ABOUT PROGRAM/n";
   int total_rec,st;
   ifstream fin;
   fin.open("database",ios::in|ios::out|ios::binary);

   /*******using manipulators*********/
   fin.seekg(0,ios::end); // goto end of file
   total_rec=fin.tellg()/sizeof(student);
   st = fin.tellg();

   cout<<"/n/ntTotal record in file of student are: "<<total_rec;
   cout<<"/ntMemory of database is: "<<st<<" byte";

   _setcursortype(_NOCURSOR); // disable mouse cursor
 }

main program start here

This is the starting point of this entire program, it is just like a simple program –

int main()
{
  char ch;
  do
  {
  gotoxy(40,5);// print message a specific location into monitor
  cout<<"SELECTION MENUn";
  gotoxy(40,7);
  cout<<"1.INSERT RECORDn";
  gotoxy(40,8);
  cout<<"2.DISPLAY RECORDn";
  gotoxy(40,9);
  cout<<"3.SEARCH RECORDn";
  gotoxy(40,10);
  cout<<"4.MODIFY RECORDn";
  gotoxy(40,11);
  cout<<"5.DELETE RECORDn";
  gotoxy(40,12);
  cout<<"6.PROPERTIESn";
  gotoxy(40,13);
  cout<<"0.EXITn";
  gotoxy(45,18);
  cout<<"Enter Your Choice: ";
  ch=getche();
  switch(ch)
  {
    case '1': obj.input_record();break;
    case '2': obj.putdata_record();break;
    case '3': obj.search_record(); break;
    case '4': obj.modify_record(); break;
    case '5': obj.delete_record();break;
    case '6': obj.total();break;
    case '0': exit(0);               //program exit
  }
 }
 while(ch!=0);
return 0;
}

OUTPUT

SELECTION MENU
        1.INSERT RECORD
        2.DISPLAY RECORD
        3.SEARCH RECORD
        4.MODIFY RECORD
        5.DELETE RECORD
        6.PROPERTIES
        0.EXIT
             Enter Your Choice:

Now, you are ready to make your own project………

If you want, you can further improve it by adding other options like database backup, reset database, database recovery, user login page, multiple user access etc. This will improve your file handling as well as your programming skill. Which is better than clearing the concept.

Related Project in C++ are:


C++ Examples

Like it?
Exit mobile version