User Menu

Login



Share with

Data File Handling PDF Print E-mail

Data File Handling

File

A file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind. The collection of bytes may be interpreted, for example, as characters, words, lines, paragraphs ,fields and records belonging to a database.

Essentially there are two kinds of files that programmers deal with text files and binary files.

Text files

A text file can be a stream of characters that a computer can process sequentially. It is not only processed sequentially but only in forward direction. For this reason a text file is usually opened for only one kind of operation (reading, writing, or appending) at any given time.

Similarly, since text files only process characters, they can only read or write data one character at a time.

Binary files

A binary file is no different to a text file. It is a collection of bytes. In C++ Programming Language a byte and a character are equivalent. Hence a binary file is also referred to as a character stream, but there are two essential differences.

1. No special processing of the data occurs and each byte of data is transferred to or from the disk unprocessed.

2. C++ Programming Language places no constructs on the file, and it may be read from, or written to, in any manner chosen by the programmer.

Binary files can be either processed sequentially or, depending on the needs of the application, they can be processed using random access techniques. In C++ Programming Language, processing a file using random access techniques involves moving the current file position to an appropriate place in the file before reading or writing data. This indicates a second characteristic of binary files. They a generally processed using read and write operations simultaneously.

For example, a database file will be created and processed as a binary file. A record update operation will involve locating the appropriate record, reading the record into memory, modifying it in some way, and finally writing the record back to disk at its appropriate location in the file.

C++ has two basic classes to handle files, ifstream and ofstream. To use them, include the header file fstream. Ifstream handles file input (reading from files), and ofstream handles file output (writing to files). The way to declare an instance of the ifstream or ofstream class is:

ifstream fin;
fin.open("filename");

or

ifstream fin( "filename" );

The default mode for opening a file with ofstream's constructor is to create it if it does not exist, or delete everything in it if something does exist in it.

ios::in   -- Open file for input mode/read mode

ios::out   -- Open file for output mode/write mode

ios::app   -- Open file for append mode
ios::binary --Open file in Binary mode
 

we can combine more than one mode at a time with |(Logical Or operator)
ofstream fout( "test.txt", ios::in|ios::out );

This will open test.txt file in input as well as in output mode simultaneously.

Open File in append mode:

ofstream fout( "test.txt", ios::app );

This will open the file without destroying the current contents and allow you to append new data.

Detecting End of File

C++ provides a special function, eof( ), that returns nonzero (meaning TRUE) when there are no more data to be read from an input file stream, and zero (meaning FALSE) otherwise.

Rules for using end-of-file (eof( )):

1.Always test for the end-of-file condition before processing data read from an input file stream.

2.Use a while loop for getting data from an input file stream.

Example of read from file and display it using eof()

#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
     ifstream fin;
     fin.open("input.txt");
     char ch;
     while(!fin.eof()) //use of eof() function
     {
          fin.get(ch);
          cout<<ch;
     }
     fin.close();
     getch();
     return 0;
}

Program to count number of words

#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
     ifstream fin;
     fin.open("input.txt");
     char words[50]; int count=0;
     while(!fin.eof())
     {
          fin>>words;
          count++;
     }
     cout<<"Number of words in file is "<<count;
     fin.close();
     getch();
     return 0;
}

Program to count number of lines

#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
     ifstream fin;
     fin.open("input.txt");
     char line[80]; int count=0;
     while(!fin.eof())
     {
          fin.getline(line,80);
          count++;
     }
     cout<<"Number of lines in file is "<<count;
     fin.close();
     getch();
     return 0;
}

Program to count number of vowels

#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
     ifstream fin;
     fin.open("input.txt");
     char ch; int count=0;
     while(!fin.eof())
     {
          fin.get(ch);

     if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
          count++;
     }
     cout<<"Number of vowels in file are "<<count;
     fin.close();
     getch();
     return 0;
}

Program to count number of digits

#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
     ifstream fin;
     fin.open("input.txt");
     char ch; int count=0;
     while(!fin.eof())
     {
          fin.get(ch);

     if(isdigit(ch))
          count++;
     }
     cout<<"Number of digits in file are "<<count;
     fin.close();
     getch();
     return 0;
}

Program to count number of line starting with alphabet ‘A’.

#include<fstream.h>
#include<iostream.h>
#include<conio.h>
int main()
{
     ifstream fin;
     fin.open("input.txt");
     char line[80]; int count=0;
     while(!fin.eof())
     {
       fin.getline(line,80);

     if(line[0]=='A')
          count++;
     }
     cout<<"Number of lines starting with A are "<<count;
     fin.close();
     getch();
     return 0;
}

Program to copy contents of one file to another file.

#include<fstream.h>
int main()
{
     ifstream fin;
     fin.open("source.txt");
     ofstream fout;
     fout.open("destination.txt");
     char ch;
     while(!fin.eof())
     {
          fin.get(ch);
          fout<<ch;
     }
     fin.close();

     fout.close();

     return 0;
}

Binary File Handling Functions

ifstream::read

ifstream& read ( char* t, int n );

Reads a block of data of n characters and stores it in the array pointed by t.

If the End-of-File is reached before n characters have been read, the array will contain all the elements read until it.
Notice that this is an unformatted input function and what is extracted is not stored as a c++ string format, therefore no ending null-character is appended at the end of the character sequence.

Parameters
t
Pointer to an allocated block of memory where the content read will be stored.

n
Integer value of type streamsize representing the size in characters of the block of data to be read. 

ofstream::write

ofstream& write ( const char* t , int n );

Writes the block of data pointed by t, with a size of n characters, into the output buffer. The characters are written sequentially until n have been written.

This is an unformatted output function and what is written is not necessarily a c++ string, therefore any null-character found in the array t is copied to the destination and does not end the writing process.

Parameters
t
Pointer to a block data with the content to be written.
n
Integer value of type streamsize representing the size in characters of the block of data to write.

Return Value

The function returns *this. 

ofstream::seekp()
ofstream& seekp ( int pos );

ofstream& seekp ( int off, ios::seekdir dir );

Sets the position of the put pointer.

The put pointer determines the location in the output sequence where the next output operation is going to take place.

Parameters
pos
The new position in the stream buffer. This parameter is an integral value.

off
Integral value representing the offset to be applied relative to an absolute position specified in the dir parameter.
dir
Seeking direction. It is an object of type ios::seekdir that specifies an absolute position from where the offset parameter off is applied. It can take any of the following member constant values:
    
   ios::beg   beginning of the stream buffer
   ios::cur   current position in the stream buffer
   ios::end   end of the stream buffer

Return Value

The function returns *this.

Example

// Position of put pointer

#include <fstream.h>

int main () {

  long pos;

  ofstream outfile;

  outfile.open ("example.txt");

  outfile.write ("My Name is Ayan",15);

  pos=outfile.tellp();

  outfile.seekp (pos-4);


  outfile.write ("Sanju",5);

  outfile.close();

  return 0;

}
In this example, seekp is used to move the put pointer back to a position 4 characters before the end of the first output operation. The final content of the file shall be:

My Name is Sanju 

ifstream::seekg()

ifstream& seekg ( int pos );

ifstream& seekg ( int off, ios::seekdir dir );

Sets the position of the get pointer.
The get pointer determines the next location to be read in the source associated to the stream.


Parameters
pos
The new position in the stream buffer. This parameter is an integral value of type streampos.
off
Integral value representing the offset to be applied relative to an absolute position specified in the dir parameter.
dir
Seeking direction. It is an object of type ios::seekdir that specifies an absolute position from where the offset parameter off is applied. It can take any of the following member constant values:

   ios::beg    beginning of the stream buffer

   ios::cur    current position in the stream buffer

   ios::end    end of the stream buffer

Return Value

The function returns *this.

Example

// load a file into memory

#include <iostream.h>

#include <fstream.h>

int main () {

  int length;

  char buffer[100];

  ifstream is;

  is.open ("test.txt", ios::binary );

  // get length of file:

  is.seekg (0, ios::end);

  length = is.tellg();

  is.seekg (0, ios::beg);

   // read data as a block:

  is.read (buffer,length);

  is.close();

  cout.write (buffer,length);

  return 0;

}

In this example seekg is used to move the get pointer to the end of the file, and then back to the beginning.

ofstream ::tellp ( );

int tellp ( );

Get position of put pointer
Returns the absolute position of the put pointer.

The put pointer determines the location in the output sequence where the next output operation is going to take place.

Return Value

An integral value of type int with the number of characters between the beginning of the output sequence and the current position.

Failure is indicated by returning a value of -1.

Example
// position of put pointer

#include <fstream.h>

 int main ()

 {

  long pos;

  ofstream outfile;

  outfile.open ("test.txt");

  outfile.write ("My Name is Ayan",15);

  pos=outfile.tellp();

  outfile.seekp (pos-4);

  outfile.write ("Sanju",5);

  outfile.close();

  return 0;

}

In this example, tellp is used to get the position of the put pointer after the writing operation. The pointer is then moved back 4 characters to modify the file at that position, so the final content of the file shall be:

My name is Sanju

ifstream::tellg()

 int tellg ( );

Get position of the get pointer.
Returns the absolute position of the get pointer.

The get pointer determines the next location in the input sequence to be read by the next input operation.

Return Value

An integral value with the number of characters between the beginning of the input sequence and the current position.
Failure is indicated by returning a value of -1.

Example of tellg()

#include <iostream.h>
#include <fstream.h>

 int main () {
  int length;
  char buffer[50];

   ifstream is;
  is.open ("test.txt", ios::binary );

  is.seekg (0, ios::end);

   // get length of file:
  length = is.tellg();
  is.seekg (0, ios::beg);

    // read data:
  is.read (buffer,length);
  is.close();
  cout.write (buffer,length);
  return 0;
}

In this example, tellg is used to get the position in the stream after it has been moved with seekg to the end of the stream, therefore determining the size of the file.

Some Basic Operations on Binary Files in C++

#include<iostream.h>

#include<string.h>

 class student
{
        int rollno;
        char name[20];
        public:
          void getdata()
          {
            cout<<"\nEnter The Roll no. ";
            cin>>rollno;
            cout<<"\n\nEnter The Name of The Student ";
            gets(name);
          }
          void showdata()
          {
            cout<<"\nRoll no. : "<<rollno;
            cout<<"\nStudent Name : ";
            puts(name);
          }
          int returnrollno()
          {
             return rollno;
          }
};

 This function will write on Binary File
 void write_data()
{
   student obj;
   ofstream fout;
   fout.open("student.dat",ios::binary|ios::app);
   obj.getdata();
   fout.write((char*)&obj,sizeof(obj));
   fout.close();
}

This function will display records
 void display()
{
     student obj;
     ifstream fin;
     fin.open("student.dat",ios::binary);
     while(fin.read((char*)&obj,sizeof(obj)))
          {
           obj.showdata();
          }
     fin.close();
}

This function will search and display from binary file

 void search (int n)
{
   student obj;
   ifstream fin;
   fin.open("student.dat",ios::binary);
    while(fin.read((char*)&obj,sizeof(obj)))
       {
        if(obj.returnrollno()==n)
           obj.showdata();
       }
   fin.close();
}

This function will delete a record

void deleterecord(int n)

   {
          student obj;
          ifstream fin;
          fp1.open("student.dat",ios::binary);
          ofstream fout;
          fout.open("Temp.dat",ios::out|ios::binary);
          while(fin.read((char*)&obj,sizeof(obj)))
          {
            if(obj.returnrollno()!=n)
            fout.write((char*)&obj,sizeof(obj));
          }
          fin.close();
          fout.close();
          remove("student.dat");
          rename("Temp.dat","student.dat");
   }

This function will modify a record

void modifyrecord(int n)
{
   fstream finout;
   student obj;
   int found=0; 
   finout.open("student.dat",ios::in|ios::out);
   while(finout.read((char*)&obj,sizeof(obj)) && found==0)
          {
             if(obj.returnrollno()==n)
              {
               obj.showdata();
               cout<<"\nEnter The New data of student";
               obj.getdata();
               int pos=-1*sizeof(obj);
               finout.seekp(pos,ios::cur);
               finout.write((char*)&obj,sizeof(obj));
               found=1;
              }
          }
    finout.close();
}

scroll back to top