Introduction to File Systems:


Until now, we have been using a console-oriented input/output system.When using a console application, once a program is terminated, the data stored in the main memory is lost. For small programs like a calculator, permanent data storage isn't necessary. However, for larger programs, such as those that display student results or calculate monthly employee salaries, data needs to be stored permanently.

When a program is created and data is entered for processing, the data stored in memory is lost after the program ends. To store data permanently, C++ provides file handling. File handling offers a mechanism to store a program's output in a file and read from a file on the disk.

So far, we have been using the <iostream>header file, which provides the cinand coutfunctions for input from the console and output to the console, respectively. In this tutorial, we introduce another header file, <fstream>which provides the following data types or classes:

ofstream

Used to create a file and write data to files.


ifstream

Used to read data from files.


fstream

Used to both read from and write data to files.

In this tutorial, we will work with objects of the fstreamtype. The fstreamclass encapsulates the properties of both the ifstreamand ofstreamclasses.

  • If we want to open a file only for input operations, we use an ifstreamobject.
  • If we want to write to a file, we use an ofstreamobject.

Our programs can access files in two ways:

The type of application determines which method we should choose. The access mode of a file determines how we read, write, change, and delete data from the file. Some files can be accessed in both ways, sequentially and randomly, as long as our programs are written properly and the data lends itself to both types of file access.

A sequential file must be accessed in the same order in which the file was written. Consider the example of cassette tapes: we play music in the same order it was recorded. We can fast-forward or rewind quickly over songs we don't want to listen to, but the order of the songs dictates how we play the desired song. However, it is difficult, and sometimes impossible, to insert data in the middle of two other songs on a tape.

The only way to truly add or delete records from the middle of a sequential file is to create a completely new file that combines both old and new records.


Read More

Unlike sequential files, random access files can be accessed in any order. Think of data in a random access file as songs on a compact disc: we can go directly to any song without having to play or fast-forward over the others. We can play the first song, then the sixth, and then the fourth in any order. The playback order is independent of the order in which the songs were originally recorded.

Random-file access sometimes requires more programming but rewards our effort with a more flexible file-access method.


Read More