File Handling

File handling is done so that  you can store any result or output to your Hard disk and read that later on.For eg:
you write a program to accept the marks of students of your class and store them in some variables.But as soon the program is over all those variables are erased from the memory thus all your data is gone.Hence you need to store them in some file from where u can read them later.This is achieved by FILE HANDLING.

Many real-life problems handle large volumes of data, therefore we need to use some devices such as floppy disk or hard disk to store the data.
The data is stored in these devices using the concept of files. A file is a collection of related data stored in a particular area on the disk.
Programs can be designed to perform the read and write operations on these files.

File IO means transfer of data from secondary memory (hard disk) to main memory or vice versa. A schematic showing the flow of data and classes involved is as follows:

fileflowNote: The arrows indicate the flow of data.

A program typically involves either or both of the following kinds of data communication:

  • Data transfer between the console unit and the program.
  • Data transfer between the program and a disk file.
    The input/output system of C++ handles file operations which are very much similar to the console input and output operations.It uses file streams as an interface between the programs and the files.

The stream that supplies data to the program is known as input stream and the one that receives data from the program is known as output stream.
In other words, the input stream extracts or reads data from the file and the output stream inserts or writes data to the file.
Classes for the file stream operations :
The I/O system of C++ contains a set of classes that define the file handling methods.

These include ifstream, ofstream and fstream.

filestreams

These classes, designed to manage the disk files, are declared in fstream.h and therefore we must include this file in any program that uses files.

Details of some useful classes :
filebuf
Its purpose is to set the file buffer to read and write. Contains openprot constant used in the open() of the filestream classes. Also contains close() and open() as member functions.

fstreambase
Provides operations common to the file streams. Serves as a base for fstream, ifstream and ofstream classes. Contains open() and close() functions.

Data Type Description
ofstream This data type represents the output file stream and is used to create files and to write information to files.
ifstream This data type represents the input file stream and is used to read information from files.
fstream This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.

To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file.

ifstream
Provides input operations. Contains open() with default input mode. Inherits the functions get(), getline(), read(), seekg() and tellg() functions from istream.

ofstream
Provides output operations. Contains open() with default output mode. Inherits put(), seekp(), tellp(), and write() functions from ostream.

fstream
Provides support for simultaneous input and output operations. Contains open() with default input mode. Inherits all the functions from istream and ostream classes through iostream.

The ifstream, ofstream and fstream classes are declared in the file fstream.h
The istream and ostream classes are also included in the fstream.h file.

OPENING FILE

To open a file we use open() command as following:

ofstream cppfile;

cppfile.open(“filename”,mode);

In the above line:

ofstream cppfile: By using ofstream we declared a file variable cppfile who used to access file.

cppfile.open (“filename”,mode): You can see that we use the file variablecppfile with open() to open a file. filename is a file which to be open and modecan be the following :

File mode Uses
ios::app Append to end of file
ios::ate go to end of file on opening
ios::binary file open in binary mode
ios::in open file for reading only
ios::out open file for writing only
ios::nocreate open fails if the file does not exist
ios::noreplace open fails if the file already exist
ios::trunc delete the contents of the file if it exist

When we use two mode at a time we have to use operator OR (|) between mode. For example, if we want to open the file example.dat in binary mode to add data we could do it by the following:

fstream myfile;
myfile.open (example.dat, ios::out | ios::app | ios::binary);

CLOSING FILE

If you have opened any file then you must close the opened file by following command:

myfile.close();

INPUT AND OUTPUT OPERATION

put() Function :

The function put() writes a single character to the associated stream.

get() Function :

Similarly, the function get() reads a single character form the associated stream.
example :

myfile.get(ch);
myfile.put(ch);

write() function :

write() function write blocks of binary data.

read() Function :

read() function read blocks of binary data.

example:

myfile.write((char *)&obj, sizeof(obj));

myfile.read((char *)&obj, sizeof(obj));

 

Read & Write Example:

Following is the C++ program which opens a file in reading and writing mode. After writing information inputted by the user to a file named afile.dat, the program reads information from the file and outputs it onto the screen:

#include <fstream>
#include <iostream>
using namespace std;
 
int main ()
{
   char data[100];

   // open a file in write mode.
   ofstream outfile;
   outfile.open("afile.dat");

   cout << "Writing to the file" << endl;
   cout << "Enter your name: "; 
   cin.getline(data, 100);

   // write inputted data into the file.
   outfile << data << endl;

   cout << "Enter your age: "; 
   cin >> data;
   cin.ignore();
   
   // again write inputted data into the file.
   outfile << data << endl;

   // close the opened file.
   outfile.close();

   // open a file in read mode.
   ifstream infile; 
   infile.open("afile.dat"); 
 
   cout << "Reading from the file" << endl; 
   infile >> data; 

   // write the data at the screen.
   cout << data << endl;
   
   // again read the data from the file and display it.
   infile >> data; 
   cout << data << endl; 

   // close the opened file.
   infile.close();

   return 0;
}

When the above code is compiled and executed, it produces the following sample input and output:

Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9

Above examples make use of additional functions from cin object, like getline() function to read the line from outside and ignore() function to ignore the extra characters left by previous read statement.

ERROR HANDLING FUNCTION

FUNCTION RETURN VALUE AND MEANING

fail()

Returns true if a reading or writing operation fails,

eof()

Returns true if a file open for reading has reached the end.

bad()

Returns true if an invalid operation are attempted, for example if you are trying to write to a file that is not opened for writing operation or that file has no space left.

good()

Returns true if no error has occurred.

File Position Pointers:

Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg (“seek get”) for istream and seekp (“seek put”) for ostream.

The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate the seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning relative to the current position in a stream or ios::end for positioning relative to the end of a stream.

The file-position pointer is an integer value that specifies the location in the file as a number of bytes from the file’s starting location. Some examples of positioning the “get” file-position pointer are:

// position to the nth byte of fileObject (assumes ios::beg)
fileObject.seekg( n );

// position n bytes forward in fileObject
fileObject.seekg( n, ios::cur );

// position n bytes back from end of fileObject
fileObject.seekg( n, ios::end );

// position at end of fileObject
fileObject.seekg( 0, ios::end );

 

Text and binary files

The C++ language supports two types of files:

  • Text files
  • Binary files

The basic difference between text files and binary files is that in text files various character translations are performed such as “\r+\f” is converted into “\n”, whereas in binary files no such translations are performed.

By default, C++ opens the files in text mode.

In the tables below we will see the various steps and operations that can (or must) be performed to use files in C++:

1)Creating or opening a file

  • For writing data
Text Filesofstream out (“myfile.txt”);orofstream out;out.open(“myfile.txt”); Binary Filesofstream out (“myfile.txt”,ios::binary);orofstream out;out.open(“myfile.txt”, ios::binary);
  • For Appending (adding text at the end of the existing file)
Text Filesofstream out(“myfile.txt”,ios::app);orofstream out;out.open(“myfile.txt”, ios::app); Binary Filesofstream out
(“myfile.txt”,ios::app|ios::binary);orofstream out;out.open(“myfile.txt”, ios::app | ios::binary);
  • For reading data
Text Filesifstream in (“myfile.txt”);orifstream in ;in.open(“myfile.txt”); Binary Filesifstream in (“myfile.txt”, ios::binary);orifstream in ;in.open(“myfile.txt”, ios::binary);

2) Closing Files (after reading or writing)

ofstream object
“out”
Ifstream object
“in”
out.close(); in.close();

3) Reading / Writing Data to and from files

Data Functions for reading
file
Function for writing
into file
char get(); put();
1
word
>>
(extraction
operator)
<< (insertion
operator)
>=1
word
getline(); << (insertion
operator)
Objects read() write()
Binary
data
Same as
above
Same as
above

4) Functions that can be used to perform special tasks

Operation function Description
Checking end of
file.
eof() Used to check eof during
the reading of file
Check if an operation
fails.
bad()

Returns true
if a reading or writing operation fails.

Check if an operation
fails.
Fail()

Returns true
in the same cases as bad(), but also in the case that a format error
happens.

Checking for opened
file.
is_open(); Checks if the file is
opened or not, returns true if the file is opened else
false
Number of bytes already
read.
gcount() Returns count of the
bytes read from the file
Ignoring characters
during file read.
ignore() Ignores n bytes from the
file. (get pointer is positioned after n
character)
Checking next
character.
peek() Checks the next available
character, will not increase the get pointer to next
character.
Random access (only for
binary files).
seekg()seekp()tellg()tellp() In case of binary files random access is performed using these functions. They either give or set the position of get and put pointers on the particular location