When a large amount of data is to be handled in such situations floppy disk or hard disk are needed 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 a disk.

Programs can be designed to perform the read and write operations on these files .

The I/O 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 files. The stream that supplies data to the program is called input stream and the one that receives data from the program is called output stream. In other words input stream extracts data from the file and output stream inserts data to the file.

The input operation involves the creation of an input stream and linking it with the program and input file. Similarly, the output operation involves establishing an output stream with the necessary links with the program and output file.

figure-6-1-file-input-and-output-stream

File Stream Classes

The I/O system of C++ contains a set of classes that defines the file handling methods. These include ifstream, ofstream and fstream.These classes are derived from fstreambase and form the corresponding iostream class. These classes ,designed to manage the disk files are declared in fstream and therefore this file is included in any
program that uses files.

figure-6-2-stream-classes-for-file-operations

Steps of File Operations

For using a disk file the following things are necessary

  • Suitable name of file
  • Data type and structure
  • Purpose
  • Opening Method

figure below show file stream classes
table-6-1-detail-of-file-stream-classes

The filename is a string of characters that makeup a valid filename for the operating system. It may contain two parts ,primary name and optional period with extension.

Examples are Input.data, Test.doc etc. For opening a file firstly a file stream is created and then it is linked to the filename.A file stream can be defined using the classes ifstream, ofstream and fstream that contained in the header file fstream.The class to be used depends upon the purpose whether the write data or read data operation is to be performed on the file.

A file can be opened in two ways:

  •  Using the constructor function of class.
  •  Using the member function open() of the class.

The first method is useful only when one file is used in the stream.The second method is
used when multiple files are to be managed using one stream.

Share with : Share on Linkedin Share on Twitter Share on WhatsApp Share on Facebook