Pages

January 31, 2013

I/O File Handling in C++ (OOPs)


Input output file handling in C++ (OOPs) banner

A File is a bunch of bytes stored on some storage device like magnetic disk or tape etc. Most of the application programs process large volume of data which is permanently stored in files. We can write programs that can read data from file(s) and write data to file(s). 


Compilers read source code files and provide executable files. Data Base programs and word processors also work with these files.

Data Transfer is generally one or both of the two types given below:
1. Transfer between console unit and the program.
2. Transfer between the program and file on disk or tape.

So, far we have used the technique of data communication between console unit and the program where the amount of data is very small. Now we are going to describe the important requirements for the need of data storage in files:

Fast Response: 

There are applications where the required information is needed very fast. In such situations if the data is stored in a file or files it can be utilized immediately without any delay.

Ease of use: 

There are different ways of utilizing the data by different users. If the data stored in a file is in the order we want to process then it becomes very easy to handle it and a lot of time and efforts are saved.

Constraints on performance:

In real time systems, there are constraints on the performance of the system. The data must be protected very fast, if not so, the data may be lost or may be of no value or there may be serious consequences e.g. in case of natural disasters like earth-quakes, floods or chemical industries, space research work, the person must be informed well in advance so that necessary action may take place.

Saving of repetitive typing of data: 

If the same type of data is needed again and again for processing we need not to type it repeatedly. E.g. the data of employees in an organisation, the data of students in a school in processed many times. The data is stored in a file(s) only once and processed for enquires on it.

Correctness of data:

The contents of a data file are verified and the errors, if any, can be removed easily. So the correctness of data is improved which helps in obtaining accurate result.


OPERATIONS THAT CAN BE PERFORMED WITH THE HELP OF FILE

Creating an empty file: 

First time when a file is created with some valid filename it is empty and therefore it contains no element except that it contains and end-of-file marker and a location pointer pointing to end-of-file.

Opening a file:

A file is opened for performing reading/writing or manipulation of data on it. If the file is not present on the disk it cannot be opened. When an existing file is opened the location pointer points to the beginning of the file.

Closing a file:

After the file is created and data elements are written to it, it should be closed or even if it is opened for reading only. If we don’t close it, the opened file is automatically closed when the program using it comes to an end.

Writing text into files: 

Once a file with some valid filename has been created, data elements or text can be stored in a file permanently. The already existing file(s) contents are deleted if we try to write data to it. Rather we can append data to it and keep the existing data.

Reading of text from an already existing text file (accessing sequentially): 

An existing file must be opened first and then the data can be read from it in sequential order.

Manipulation of text file from an already existing text file (accessing sequentially): 

An existing file must be opened first and then the manipulation is done in sequential order. E.g. counting of vowels etc.

Detecting end-of-file: 

When the data from the file is read in sequential order, the location pointer will reach to the end-of-file no attempts should be made to read data from the file.

OPENING OF A FILE

By using open() function having syntax

ifstream in_file;
in_file.open(“Filename.ext”);

ofstream out_file;
out_file.open(“Filename.ext”);

By using constructors having syntax

ifstream in_file(“Filename.ext”);
ofstream out_file(“Filename.ext”);

By using read() and write() functions having syntax

stream object_name.open(“Filename”,file_mode);

use of pointers in input output file handling in C++ (OOPs)

various operation modes used in input output file handling in C++ (OOPs)

/* Program to show how to operate open() function in file handling*/

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
main()
{
      char ch[100],ch1[100];
      cout<<"\n Enter anything in the character format\n ";
      gets(ch);
      ofstream enter("File.txt");
      enter<<ch;
      ifstream display("File.txt");
      while(!display.eof())
      {
      display>>ch1;
      cout<<"\n Data entered in the file is: "<<ch;
      }
      cout<<"\n\n Now press ENTER to see the entered data in the file";
      getch();
      }
output of program to show use of open function using constructors in file handling and save it in file in C++ (OOPs)
output of program to show use of open function using constructors in file handling and save it in file in C++ (OOPs)


/* Program to read and write data from file */

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
main()
{
      char ch[100],ch1[100];
      cout<<"\n Enter anything in the character format\n ";
      gets(ch);
      ofstream enter;
      enter.open("File.txt");
      enter<<ch;
      ifstream display;
      display.open("File.txt");
      while(!display.eof())
      {
      display>>ch1;
      cout<<"\n Data entered in the file is: "<<ch;
      }
      cout<<"\n\n Now press ENTER to see the entered data in the file";
      getch();
      }
output of program to show how to read and write data form the files using file handling in C++ (OOPs) using open function
output of program to show how to read and write data form the files using file handling in C++ (OOPs) using open function


/* Program to perform add operation and save it in file*/

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
class add
{
      public:
             int a,b,c;
      void enter()
      {
           cout<<"\n Enter any two integer values";
           cin>>a>>b;
           c=a+b;
           }
      void display()
      {
           ofstream show;
           show.open("Addition.txt",ios::out|ios::app);
           cout<<"\n Addition of "<<a<<" and "<<b<<" is "<<c;
           show<<"\n Addition of "<<a<<" and "<<b<<" is "<<c;
           }
};
main()
{
      class add s;
      s.enter();
      s.display();
      getch();
      }
output of program to perform addition operation and save the result in file in C++ (OOPs)
output of program to perform addition operation and save the result in file in C++ (OOPs)

 
      

/* Program to display student details and save in a file*/

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
      
main()
{
   char nm[20][10],clas[10][10];
   int age[10],n,i;
   cout<<"\n How many student's data you want to enter";
   cin>>n;
   for(i=1;i<=n;i++)
   {
         cout<<"\n Enter "<<i<<" student name, age and class";
         cin>>nm[i]>>age[i]>>clas[i];
                    }
   cout<<"\n\n ";
   ofstream st1;
   st1.open("Student.txt",ios::out);
   cout<<"\n Sr.\tAge\tName\t   Class";
   st1<<"\n Sr.\tAge\tName\tClass";
   for(i=1;i<=n;i++)
   {
     cout<<"\n "<<i<<"\t"<<age[i]<<"\t"<<nm[i]<<"\t   "<<clas[i];
     cout<<"\n ";
     st1<<"\n "<<i<<"\t"<<age[i]<<"\t"<<nm[i]<<"\t   "<<clas[i];
     st1<<"\n ";
        }
     getch();
     }
output of program to show student details and save it in file in C++ (OOPs)
output of program to show student details and save it in file in C++ (OOPs)

 

/* Program to set up a matrix and save it in file*/

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
class matrix
{
      public:
             int i,j,n,m,a,x[10][10];
      void enter()
      {
           cout<<"\n Enter the order of a matrix n*m";
           cin>>n>>m;
           a=m*n;
           cout<<"\n Enter "<<a<<" elements";
           for(i=0;i<n;i++)
           {
                           for(j=0;j<m;j++)
                           {
                                           cin>>x[i][j];
                                           }
                                           }
                                           }
      void display()
      {
           ofstream show;
           show.open("Matrix.txt",ios::out);
           cout<<"\n A: ";
           show<<"\n A: ";
           for(i=0;i<n;i++)
           {
                           for(j=0;j<m;j++)
                           {
                                           cout<<x[i][j]<<" ";
                                           show<<x[i][j]<<" ";
                                           }
                           cout<<"\n    ";
                           show<<"\n     ";
                           }
                           }
};
main()
{
      class matrix mt;
      mt.enter();
      mt.display();
      getch();
      }
output of program to enter order and display elements in the matrix and save the result in file in C++ (OOPs)
output of program to enter order and display elements in the matrix and save the result in file in C++ (OOPs)

                                           
           

ERROR HANDLING FUNCTIONS FOR FILEs

In C++, we have a large number of functions to handle the errors that may occur during file input/output operations. These errors may include:
1. Attempt to read a non-existing file.
2. Attempt to read past the end-of-file.
3. Attempt to create a file that already exists on the disk.
4. Non-availability of space on the disk for storing a file.
5. Use of invalid file name.
6. Attempting an input/output operation on a file without opening it.

error handling functions used in input output file handling in C++ (OOPs)

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. A file is a collection of related data stored in a particular area on the disk. The data is stored in disk using the concept of file. In c++ we can easily handle file for store data permanently.File Handling in C++

    ReplyDelete