In the article of file handling in C++ we will discuss following,
File handling in C++
In simple words, in file handling, we create a file through a program, which stores in internal storage such as hard-disk and in this file we store the information given by the end-user.
In a way, you can say that this file acts as a database in C ++. In this file we store the user-input which remains in the internal storage even after the program terminates and this data can be accessed again by re -execute the program and it can also be manipulated like modify, delete, search etc.
Let us understand this in detail.
why we use file-handling? benefit of 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 information in memory. But this information is stored only in memory as long as the program remains in execution, as soon as the program terminates, this information is also removed.
But if we want the information to be stored in the memory by the end-user even after the program is terminated. So for this in C ++ we use file handling concept.
writing and reading a file
Before using file handling in a program, we have to include its header file in the program-
fstream
Like in other programs cout
is used for output and cin
statement is used for input.
Similarly, file handling consists of two stream-objects (sequence of byte), using output-stream to print stored-data from a file and input -stream to write data into a file.
As you can see in the following diagram –
But remember where cout
and cin
are reserved keywords, whereas here both output and input-stream will be identifiers. That is, any appropriate name.
Implementation of a file in a program
For file handling in a program, we have to keep a few points in mind –
- file name and its extension type
- C++ stream class
- Closing the file
File name and its extension type
The filename can be any appropriate name, that is, user defined name, here the file extension is optional. But if you give the extension, the program will create the type of file extension type such as
student.txt // text file will be created
student.pdf // PDF file will be create
student.doc // Ms word file will be created
student // normal file will be created, which will be opened in notepad.
C++ stream class
When we use a file, first we have to define its stream class. This stream class indicates for what purpose the file is used.
Here are some stream-class and their purpose, given below-
stream class | Task |
---|---|
ofstream |
To write the file only, |
ifstream |
To write the file only, |
fstream |
To write and read a file simultaneously, |
Open a file in Two ways
- In the program, we can open a file in two ways like
By using stream-class and stream-object in a 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 files with the same stream-object whereas, for a 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 defined inside fstream
header file.
syntax
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 reserved keyword).
How to store records in internal storage from a program
The 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.
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 in C++
here we will 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 executes,
#include<iostream>
#include<fstream>
#include<stdio.h> //for gets()
using namespace std;
int main() // main function
{
/*writing file into database file*/
char name[20];
ofstream fout("database.txt"); // open database file for writing only
cout<<"Enter Name: ";
gets(name);
fout<<name; // write to file
fout.close();
/*reading record from database file*/
ifstream fin("database.txt"); // open database file for reading only
cout<<"Displaying record from file: ";
fin>>name; // fetch data from file
cout<<name; //display
fin.close();
return 0;
}
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
Three way to write and read a file
- write file using insertion and extraction operator
- write file using put() and get(),
- write file using write() and read()
write and read a single file using put and get function
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. put()
will write the file while get()
will read the data.
Its syntax is given below –
syntax
stream_object.put(character); // to write a file
stream_object.get(character);// to read a file
Here is the program,
#include<iostream>
#include<fstream>
#include<stdlib.h>
#include<stdio.h>
#include<string.h> // for strlen();
using namespace std;
int main()
{
/*writing file*/
char name[45]; int len;
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();
return 0;
}
OUTPUT
Enter name: Rahul_sherma
Displaying record from file: Rahul_sherma
file handling Parameters
So far, you must have known from the above example, that the data in the file is storing only one time, that is, in each new execution, the program is storing 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 of 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 name | Task |
---|---|
ios::out |
only for writing a file |
ios::in |
only for reading a file |
ios::app |
to store large volume of data in a file |
ios::ate |
goto the end of the file |
ios::nocreate |
to check file create or not |
ios::trunc |
to erase all content of the file |
ios::binary |
to store record into binary form |
remember, the file’s writing and reading mode are by default is as in the example above, in which we have not used any type of mode, still have written and read the file
In a program, the syntax to use the parameter is given below –
stream-class stream-object("file-name",parameter);
Store Large Volume of data in a file
let’s try an example where we use ios::app
mode to store large volume of data,
#include<iostream>
#include<fstream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int main()
{
/*writing record into file */
char name[45];
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();
return 0;
}
OUTPUT
1st Execution
Enter name: Rahul_sherma
Displaying record from file: Rahul_sherma
2nd Exection
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 the file,
manipulators in file handling
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 | Task |
---|---|
seekg(); |
to read at or from a 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("file-name", );
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 file handling exercise.
First of all, we will open the file-
Three ways have been told to write and read a file, in which two have already been told, the syntax of the third is given below –
steam-class.stream-object;
stream-object.open(filename,mode);
To write a file,
stream-object.write((char *)&variable, sizeof(variable);
To read a 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.
There is program in file handling exercise 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 are both syntax,
for rename
rename (old-file-name, new-file-name);
for remove
remove (filename);
use of these two function we need to include header file stdio.h
in the program. These three operations are performed in the single program below,
Here is the program,
#include<iostream>
#include<fstream>
#include<stdio.h> // rename, remove
using namespace std;
int main()
{
char name[20],filename[20],newname[20];
/*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";
cout<<"\nEnter new name: ";
gets(newname);
rename(filename,newname);
cout<<"\nNow file name is: "<<newname<<endl;
/*remove file*/
cout<<"\nHit to remove file\n";
remove(newname);
cout<<"\nfile removed successfully...";
}
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...
Note: remember, if we use binary mode ios::binary
, 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,
The data in a file is stored in two ways, binary format and character format, where the character format is by default.
character format and binary format which format should you choose for data storage.
Related exercise
- creating a class name is student
- To insert record in the file
- To display record from in the file
- To Delete Record From a file
- To search a specific record in the file
- To modify a specific record in the file
- To calculate Total record in the file
Previous – inheritance and their types in C++