file handling in C++

In this Page we will discuss following topics,

 

Why we use file-handling?

As we know that in a program, we store the information given by the user in a variable and the variable stores these informations in memory, but this information store only in memory, as long as The program remains in execution and as soon as the program exit, this information is also removed.

But if we want the user to store the information even after the program exits, then in C++, we can use file handling.

 

File handling

in simple language, in file handling, we create a file through a program and in this file we save the information given by the user.

In a way you can say that, this file acts like a database in C ++. In this file, we store user-input which remains in internal storage even after the program exits, as well as the data can be accessed again from the same program.
And data can be manipulated, such as modification, delete, search etc.operation are possible.

 

writing and reading a file

Before using file handling in a program, we have to define its header file <fstream.h>. just ike other programs such as cout is used for output and cin is used for input.

Similarly in file handling, there are output-stream and input stream. In this, the output-stream stores the data in the file, while the input-stream access the data from the file.

Here is the diagram, below

storing-record-into-file

just like in cout and cin statement, But remember, where in C++, these statements (cout and cin) are system-defined Whereas the file handling output and input statement name, are an identifier i.e. any user defined appropriate name(except reserve keyword).

 

implementation of a file in a program

To open a file in a program, we have to keep some things in mind like-

  • file name and its extension,
  • opening method

filename and its extension type

Such as filename, one can be a suitable name, ie, user-defined name. The extension type of the file is optional, it depends on you whether you give the extension or not.

That is, a file will be created without extension, but if you give an extension, that type of file will be created. The type of file extension will be, such as: –

student.txt // text file will be create
student.pdf // PDF file will be create
student.doc // Ms word file will be create 
student // normal file will be create, which will be opened in notepad.

opening method

When we open a file, first we have to define its stream class. This stream class describes for what purpose the file is opened.

Here is some stream-class and their purpose,given below-

ifstream - for reading
ofstream - for writing
fstream - for both, reading and  writing

Opening file

In the program, we can open a file in two ways like: –

  • By using stream-class and stream-object in single statement, with direct filename , such as-
stream_class stream_object(filename);
  • In this, we first declare the stream-object of the stream-class, then by giving an open command with the same stream-object in the next statement, such as-
stream_class.stream_object;
stream_object.open(filename);

The second option is used when we open multiple file with the same stream-object whereas for single file, the first option will be used.

As soon as we write the open command of the file, the file is created automatically, so there is no separate command to create the file.

Closing a file

To close the file, the close() function is used with the stream-object which is already define inside fstream.h header file.

SYNTEX:

stream-object.close(); 

 stream-object is a sequence of byte, that used to fetch the data from internal storage such as hard-disk and its also an identifier, i.e. any appropriate name (excluding the reserve keyword).

 

How to store data in an internal storage from a program

In below diagram, you can see that the data inputted from the keyboard is displayed on the monitor screen, from the cout statement, and in file handling, the data is stored in the internal storage from the stream-object.

file-handling

Note, Here the cout statement only shows the data on the monitor screen while the stream-object will save the data in internal storage. Both are different.

Let’s try with an example, here

 

write a single file using insertion(<<) and extraction operator(>>)

Example:-

In this program, input (name) is taken from the user and stores it in a file called database). Which will be created automatically as soon as the program execute,

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdio.h>           //for gets()

void main() // main function
{

/*writing file into database file*/

    char name[20];
    clrscr();
    ofstream fout("database.txt"); // open database file for writing only

    cout<<"Enter Name: ";
    gets(name);
    fout<<name;
    fout.close();

/*reading record from database file*/

    ifstream fin("database.txt"); // open database file for reading only

    cout<<"Displaying record from file: ";
    fin>>name;
    cout<<name;
    fin.close();

getch();
}
OUTPUT:-
Enter name: Rahul_sherma
Displaying record from file: Rahul_sherma

 

The file in c ++ can also be written and read in another way. Some of these are as follows

 

write and read a single file using put() and get()

From put(), write to file and read from get(). put() stores the data in a file by having one character (single character) and get() reads that data in the file one by one (single character).

In this we will use a loop to read a file.

SYNTEX:-

stream_object.put.(character); // to write file
stream_object.get(character);// to read file

Here is the program,

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h> // for strlen();

void main()
{

/*writing file*/
      char name[45]; int len;
      clrscr();

      ofstream fout("database.txt");
      cout<<"Enter Name: ";
      gets(name);

      len = strlen(name); // calculate length of name

      for(int i=0; i<len; i++)
      {
         fout.put(name[i]); // write file one by one character using put()
       }
      fout.close();

/*reading file*/
       char ch;//int size=30;
       ifstream fin("database.txt");
       cout<<"Displaying record from file: ";

       while(!fin.eof()) // end of file
       {
         fin.get(ch);  // read file one by one character
        // or fin.getline(name,size); // read file using a line depend on size

         cout<<name;
       }
       fin.close();

getch();
}
OUTPUT:-
Enter name: Rahul_sherma
Displaying record from file: Rahul_sherma

 

Parameters

So far, you must have known from the above example, that the data in the file is saving only one time, that is, in each new execution the program is saving the new data and also removing the enter data in the previous execution. From which we can not save a large volume data in the file.

In file handling, different modes of opening the file are given using which we can store large volume data in a file. In this, the file is opened as before, only after the filename, the mode has to be defined.

These opening modes are described in the table below.

Parameter-mode Description
ios::out Only for writing
ios::in Only for reading
ios::app to store large volume data in a file
ios::ate goto the end of the file
ios::nocreate to check, file create or not
ios::noreplace open failed if file already created
ios::trunc to removing all content of the file
ios::binary to store record into binary form

remember, the file’s writing and reading mode by default are as in the example above, in which we have not used any type of mode, still have written and read the file

Example:-

store large volume of data in a file

let’s try an example where we use ios::app mode to store large valume data,

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdlib.h>
#include<stdio.h>

void main() 
{
/*writing record into file */
   char name[45];
   clrscr();

   ofstream fout("data.doc",ios::app); // using app(append) mode to store data multiple execution
   
    cout<<"Enter Name: ";
   gets(name);
   fout<<name;
   fout.close();

/*reading record from file*/
   const int size=80; char ch[50];
   ifstream fin("data.doc");

   cout<<"Displaying record from file: \n";
   fin>>name;
   cout<<name<<" ";
   fin.close();

   getch();
}
OUTPUT:-

1st execution
Enter name: Rahul_sherma
Displaying record from file: Rahul_sherma

2nd execution
Enter name: rakesh_sherma
Displaying record from file: Rahul_sherma rakesh_sherma

explanation

as you can see in the program output, here we have executed the program twice

In the 1st execution, we store a name rahul sherma , and in the 2nd execution different name rakesh sherma, both record stored in a single file called data.doc,

in the second execution we can see their two different name available in the file,That is, in the first execution, the entered data(rahul sherma) is not removed, thus we can store more data into file,

 

Manipulators for file

In C++, there are some manipulators available for the file, using which we can do operations like, how much data store is there in a file or write the data, in specific location in the file.

These manipulators are as follows-

GET-POINTER OPERATION
seekg(); to read at or from specific location in a file
tellg(); to give current position in input stream (in byte)
PUT-POINTER
seekp(); to write at a specific location in a file
tellp(); to give current position in output stream(in byte)
PARAMETER
ios::beg go to the beginning of the content in the file
ios::cur go to the current content in the file
ios::end go to the end of content in the file

Remember, seekg(), tellg() will be used with input stream (ifstream) while seekp(), tellp() will be used with output stream (ofstream).

let us understand this by example,

For example, if we have stored 50 student data in a file named student, then how to calculate these record in the file,

istream fin;
fin.open("student.txt", );
fin.seekg(0,ios,::end);
int total = fin.tellg()/sizeof (class_name);

Here the total value will be 50, meaning using this we can also calculate the store data in the file.

In this way, by using other manipulators, we can also find the size of the file. Some of these manipulators are used in a mini project.

First of all, we will open the file-

steam-class.stream-object;
stream-object.open(filename,mode);

To write file,

stream-object.write((char *)&variable, sizeof(variable);

To read file,

stream-object.read((char *)&variable, sizeof(variable);

or sometimes,

stream-object.write((char *)&class-object, sizeof(class-name);

In which the first parameter is the address of variable and the second parameter is the size of variable.

Here is a mini project (in the exercise section), which is storing student record (roll no, student name, father name, mother name). It has been expended so that it can be easily understood.

In this you will find some option menu-

insert record
Display record
Search record
Modify record
Delete record
Properties
Exit

 

user-defined filename, remove a file, rename a file

using another operator in C++, we can remove and rename a file. These functions we use will not be the function of the file handling library but they can be used.

Here is both syntex,

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

These three operations are performed in the single program below,

But here you have to minimize the turbo for the output of this program and open the turbo’s bin directly in another window. Then you will see how the program is being implemented.

Here is the program,

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdio.h>
void main() 
{
char name[20],filename[20],newname[20];
clrscr();

/*create filename*/
  cout<<"Enter file-name to create: ";
    gets(filename);
    ofstream fout(filename);

/*save record into file*/
  cout<<"\nEnter a name to store in it: ";
    gets(name);
    fout<<name;
    fout.close();
    cout<<"\nrecord saved into file called - "<<filename<<endl;

/*rename file*/
    cout<<"\nHit to Rename this file";
    getch();
    cout<<"\nEnter new name: ";
    gets(newname);
    rename(filename,newname);
    cout<<"\nNow file name is: "<<newname<<endl;

/*remove file*/   
    cout<<"\nHit to remove file\n";
    getch();
    remove(newname);
    cout<<"\nfile removed successfully...";
    getch();
}
OUTPUT:-
Enter file-name to create: database

Enter a name to store in it: rahul

record saved into file called - database

HIT ENTER to Rename this file
Enter new name: file

Now file name is: file

HIT ENTER to Remove file

file removed successfully...

remember, if we use binary mode, the data in the file will be stored in binary form which can be accessed more quickly than other normal files and its size is also reduced.

more about file handling,

related execise


previous-inheritance and their types