A file is basically a set of records stored on your computer's secondary memory. There may be situations requiring a program to open more than one file. The strategy for opening multiple files depends upon how they will be used. If the situation requires simultaneous processing of two files, then you need to create a separate stream for each file. However, if the situation demands sequential processing of files (i.e., processing them one by one), then one can open a single stream and associate it with each file in turn. To use this approach, declare a stream object without initializing it, and then use a second statement to associate the stream with a file.

For instance,

The above code lets you read two files in succession. Note that, the first file is closed before opening the second file. This is necessary because a stream can be connected to only one file at a time.

Example: Program to open multiple files simultaneously.

Output:

File Modes

A file mode describes how a file is to be used; read, write, append and so on. When you associate a stream with a file, either by initializing a file stream object with a file name or by using the open( ) method, you can provide a second argument specifying the file mode which are as follows,

The second argument of open( ) method, filemode, is of type int. A file-mode can be any of the several constants defined in the ios class. List of various file-modes is given below,

Name

Description

ios::in

Open file to read.

ios::out

Open file to write.

ios::app

All the data you write, is attached to the end of the file. It calls ios::out.

ios::ate

All the data you write, is attached to the end of the file. It does not call ios::out.

ios::trunc

Deletes all previous contents from the fie. (empties the file).

ios::nocreate

If the file does not exist, opening it with the open() function gets impossible.

ios::noreplace

If the file exists, trying to open it with the open() function, returns an error.

ios::binary

Opens a file in binary mode.

Closing a File

A file is closed by disconnecting it from the stream which is associated with it. The close() function accomplishes this task, its general form is,

For example, if a file called Master.txt is connected with an ofstream object fout then its connection with the stream can be terminated by the following statement,

fout.close() ;