At times it is required to store data on hard disk or floppy disk in some application program. The data is stored in these devices using the concept of file.

### File

A file is a collection of logically related records. A program usually requires two types of data communication.

1. Writing data on the datafile:

The data flows from keyboard to memory and from memory to storage device.

keyboard —> memory —> hard disk/floppydisk

This is called output stream where stream is the flow of data and requires an ofstream.h header file.

The data flows from storage device to memory and from memory to output device, particularly monitor.

datafile —> memory — > output device (screen)

This is called input stream and requires ifstream.h header file.

If both input stream and output stream are used in the same program, then header file fstream.h is required. If header file fstream.h is included in the program, there is no need to include iostream.h explicitly.

### Opening a File

A file can be opened in two ways:

1. Using constructor function of a class.
2. Using the member function open() of the class.

### Opening a file using constructor function

The following statement opens the file STU.DAT in output mode, i.e., for writing data on the file.

ofstream outfile(“STU.DAT”);

ofstream is a class available in the compiler file. outfile is any user defined object.

Example

The following program uses a single file for both writing and reading purposes. First, it takes the data form the keyboard and writes it to the file. After the writing is completed, the file is closed. The program again opens the same file, reads the information already written to it and displays it on the screen.

#include <fstream.h>
void main()
{ char name[30];
int rn, marks;
ofstream outfile(“INF”);
cout << “Enter student name”;
cin >> name;
cout << “Enter student roll number”;
cin >> rn;
cout << “Enter student marks”;
cin >> marks;
outfile << name << “\n”;
outfile << rn << “\n”;
outfile << marks << “\n”;
outfile.close();
ifstream infile(“INF”);
infile >> name;
infile >> rn;
infile >> marks;
cout << “Name” << name << “\n”;
cout << “Roll no” << rn << “\n”;
cout << “Marks” << marks << “\n”;
infile close();
}

### Opening a file using open() function

The function open() can be used to multiple files that use the same stream object. First a stream object is assigned to and then it is used to open the file in turn. For example:

ofstream outfile;
outfile.open(“ABC”);
_ _ _ _ _
outfile.close();
outfile.open(“XYZ”);
_ _ _ _ _
outfile.close();

### Close() function

The file should be closed at the end if it is opened either through constructor or open() function.