C++ Opening and Closing Files

In C++, you open a file, you must first obtain a stream. There are the following three types of streams:

  • input
  • output
  • input/output

Create an Input Stream

To create an input stream, you must declare the stream to be of class ifstream. Here is the syntax:

ifstream fin;

Create an Output Stream

To create an output stream, you must declare it as class ofstream. Here is an example:

ofstream fout;

Create both Input/Output Streams

Streams that will be performing both input and output operations must be declared as class fstream. Here is an example:

fstream fio;

Opening a File in C++

Once a stream has been created, next step is to associate a file with it. And thereafter the file is available (opened) for processing.

Opening of files can be achieved in the following two ways :

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

The first method is preferred when a single file is used with a stream. However, for managing multiple files with the same stream, the second method is preferred. Let's discuss each of these methods one by one.

Opening File Using Constructors

We know that a constructor of class initializes an object of its class when it (the object) is being created. Same way, the constructors of stream classes (ifstream, ofstream, or fstream) are used to initialize file stream objects with the filenames passed to them. This is carried out as explained here:
To open a file named myfile as an input file (i.e., data will be need from it and no other operation like writing or modifying would take place on the file), we shall create a file stream object of input type i.e., ifstream type. Here is an example:

ifstream fin("myfile", ios::in) ;

The above given statement creates an object, fin, of input file stream. The object name is a user-defined name (i.e., any valid identifier name can be given). After creating the ifstream object fin, the file myfile is opened and attached to the input stream, fin. Now, both the data being read from myfile has been channelised through the input stream object.

Now to read from this file, this stream object will be used using the getfrom operator (">>"). Here is an example:

char ch;
fin >> ch ;       // read a character from the file
float amt ;
fin >> amt ;       // read a floating-point number form the file

Similarly, when you want a program to write a file i.e., to open an output file (on which no operation can take place except writing only). This will be accomplish by

  1. creating ofstream object to manage the output stream
  2. associating that object with a particular file

Here is an example,

ofstream fout("secret" ios::out) ;     // create ofstream object named as fout

This would create an output stream, object named as fout and attach the file secret with it.

Now, to write something to it, you can use << (put to operator) in familiar way. Here is an example,

int code = 2193 ;
fout << code << "xyz" ;    /* will write value of code
            and "xyz" to fout's associated
            file namely "secret" here. */

The connections with a file are closed automatically when the input and the output stream objects expires i.e., when they go out of scope. (For example, a global object expires when the program terminates). Also, you can close a connection with a file explicitly by using the close() method :

fin.close() ;     // close input connection to file
fout.close() ;     // close output connection to file

Closing such a connection does not eliminate the stream; it just disconnects it from the file. The stream still remains there. For example, after the above statements, the streams fin and fout still exist along with the buffers they manage. You can reconnect the stream to the same file or to another file, if required. Closing a file flushes the buffer which means the data remaining in the buffer (input or output stream) is moved out of it in the direction it is ought to be. For example, when an input file's connection is closed, the data is moved from the input buffer to the program and when an output file's connection is closed, the data is moved from the output buffer to the disk file.

Opening Files Using Open() Function

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 you can open a single stream and associate it with each file in turn. To use this approach, declare a stream object without initializing it, then use a second statement to associate the stream with a file. For example,

ifstream fin;                        // create an input stream
fin.open("Master.dat", ios::in);     // associate fin stream with file Master.dat
:                                    // process Master.dat                       
fin.close();                         // terminate association with Master.dat

fin.open("Tran.dat", ios::in);       // associate fin stream with file Tran.dat
:                                    // process Tran.dat
fin.close();                         // terminate association

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

The Concept of File Modes

The filemode describes how a file is to be used : to read from it, to write to it, to append it, 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, as mentioned below :

stream_object.open("filename", (filemode) ) ;

The second method argument of open(), the filemode, is of type int, and you can choose one from several constants defined in the ios class.

List of File Modes in C++

Following table lists the filemodes available in C++ with their meaning :

Constant Meaning Stream Type
ios :: in It opens file for reading, i.e., in input mode. ifstream
ios :: out It opens file for writing, i.e., in output mode.
This also opens the file in ios :: trunc mode, by default.
This means an existing file is truncated when opened,
i.e., its previous contents are discarded.
ios :: ate This seeks to end-of-file upon opening of the file.
I/O operations can still occur anywhere within the file.
ios :: app This causes all output to that file to be appended to the end.
This value can be used only with files capable of output.
ios :: trunc This value causes the contents of a pre-existing file by the same name
to be destroyed and truncates the file to zero length.
ios :: nocreate This cause the open() function to fail if the file does not already exist.
It will not create a new file with that name.
ios :: noreplace This causes the open() function to fail if the file already exists.
This is used when you want to create a new file and at the same time.
ios :: binary This causes a file to be opened in binary mode.
By default, files are opened in text mode.
When a file is opened in text mode,
various character translations may take place,
such as the conversion of carriage-return into newlines.
However, no such character translations occur in file opened in binary mode.

If the ifstream and ofstream constructors and the open() methods take two arguments each, how have we got by using just one in the previous examples ? As you probably have guessed, the prototypes for these class member functions provide default values for the second argument (the filemode argument). For example, the ifstream open() method and constructor use ios :: in (open for reading) as the default value for the mode argument, while the ofstream open() method and constructor use ios :: out (open for writing) as the default.

The fstream class does not provide a mode by default and, therefore, one must specify the mode explicitly when using an object of fstream class.

Both ios::ate and ios::app place you at the end of the file just opened. The difference between the two is that the ios::app mode allows you to add data to the end of the file only, when the ios::ate mode lets you write data anywhere in the file, even over old data.

You can combine two or more filemode constants using the C++ bitwise OR operator (symbol |). For example, the following statement :

ofstream fout;
fout.open("Master", ios :: app | ios :: nocreate);

will open a file in the append mode if the file exists and will abandon the file opening operation if the file does not exist.

To open a binary file, you need to specify ios :: binary along with the file mode, e.g.,

fout.open("Master", ios :: app | ios :: binary);


fout.open("Main", ios :: out | ios :: nocreate | ios :: binary);

Closing a File in C++

As already mentioned, a file is closed by disconnecting it with the stream it is associated with. The close() function accomplishes this task and it takes the following general form :


For example, if a file Master is connected with an ofstream object fout, its connections with the stream fout can be terminated by the following statement :

fout.close() ;

C++ Opening and Closing a File Example

Here is an example given, for the complete understanding on:

  • how to open a file in C++ ?
  • how to close a file in C++ ?

Let's look at this program.

/* C++ Opening and Closing a File
 * This program demonstrates, how
 * to open a file to store or retrieve
 * information to/from it. And then how
 * to close that file after storing
 * or retrieving the information to/from it. */

void main()
   ofstream fout;
   ifstream fin;
   char fname[20];
   char rec[80], ch;

   cout<<"Enter file name: ";
   cin.get(fname, 20);

   fout.open(fname, ios::out);

      cout<<"Error in opening the file "<<fname;

   cout<<"\nEnter a line to store in the file:\n";
   cin.get(rec, 80);
   cout<<"\nThe entered line stored in the file successfully..!!";
   cout<<"\nPress any key to see...\n";

   fin.open(fname, ios::in);
      cout<<"Error in opening the file "<<fname;
      cout<<"\nPress any key to exit...";

   fin.get(rec, 80);
   cout<<"\nThe file contains:\n";
   cout<<"\n\nPress any key to exit...\n";


Here is the sample run of the above C++ program:

c++ opening and closing a file

More Examples

Here are some example programs of C++ listed, that you can go for. These programs uses file:

C++ Online Test

« Previous Tutorial Next Tutorial »

Like/Share Us on Facebook 😋