C++ Opening and Closing Files

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

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 a class ofstream. Here is an example:

ofstream fout;

Create input and 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, the next step is to associate a file with it. Following that, the file is ready (opened) for processing.

The 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 a File Using Constructors

We know that a constructor of a class initializes an object of its class when it is being created. In the 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 (data will be required from it and no other operations such as writing or modifying will be performed on the file), we will create a file stream object of input type, i.e., an ifstream type. Here is an example:

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

The preceding statement creates a "fin" object from an 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 sets of data being read from myfile have been channeled 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 from the file.

Similarly, when you want a program to write a file, i.e., open an output file (on which no operation can take place except writing only), this will be accomplished 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.txt" ios::out);      // create an ofstream object called fout

This would create an output stream with an object named "fout" and attach the file secret.txt to it. To add something to it, use << (put to operator) in the usual way. Here is an example:

int code = 2193;
fout << code;        /* writes the value of "code"
                      * to fout's associated file,
                      * namely "secret.txt" here.
                      */

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

fin.close();       // Disconnect the input connection from the file
fout.close();      // Disconnect the output connection from the file

Closing such a connection does not eliminate the stream; it just disconnects it from the file. The stream is still 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 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 disc file.

Opening Files Using the Open() Function

There may be situations requiring a program to open more than one file. The strategy for opening multiple files depends on how they will be used. If the situation requires the 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 the fin stream with the file Master.dat
:                                    // process Master.dat   
fin.close();                         // terminate the association with Master.dat

fin.open("Tran.dat", ios::in);       // Connect the fin stream to the Tran.dat file
:                                    // process Tran.dat
fin.close();                         // terminate the association or connection

The above code lets you handle reading two files in succession. Note that the first file is closed before opening the second one. It is best practice to close or terminate a file's association that is no longer in use in the current program before opening another.

The Concept of File Modes

The file mode 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 Opening Modes in C++

The table below describes the file modes available in C++ and their meanings:

Constant Meaning Stream Type
ios::in It opens the file for reading, i.e., in input mode. ifstream
ios::trunc This value causes the contents of a pre-existing file with the same name to be truncated to zero length. ofstream
ios::out It opens the file for writing, i.e., in output mode.
This also opens the file in "ios::trunc" mode, by default.
ofstream
ios::ate When the file is opened, this seeks to end-of-file.
I/O operations can still occur anywhere within the file.
ofstream
ifstream
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.
ofstream
ios::nocreate This causes the open() function to fail if the file does not already exist.
It will not create a new file with that name.
ofstream
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 at the same time.
ofstream
ios::binary This causes a binary mode file to be opened. Files are opened in text mode by default. ofstream
ifstream

Please note: When a file is opened in text mode, various character translations may occur, such as carriage-return to newline conversion. In contrast, no such character translations occur in a binary file.

If the ifstream and ofstream constructors and the open() methods take two arguments each, how have we gotten 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; therefore, the mode must be specified explicitly when using a fstream object.

Both ios::ate and ios::app place you at the end of the newly opened file. The ios::app mode only allows you to add data to the end of the file, whereas the ios::ate mode allows you to write data anywhere in the file, including over old data.

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

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

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

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);

or,

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

Closing a File in C++

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

stream_object.close();

For example, if a file "master.dat" is connected to an "ofstream" object, say "fout," its connections with the stream "fout" can be terminated by the following statement:

fout.close();

C++ Opening and Closing a File Example

For your complete understanding, here is an example regarding:

Let's take a look at this program.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
   ofstream fout;
   ifstream fin;
   string fname, rec;

   cout << "Enter file name: ";
   getline(cin, fname);

   fout.open(fname, ios::out);          // open the file for writing from the beginning.
   if (!fout)
   {
      cout << "Error opening the file!\n";
      return 0;
   }
   cout << "\nEnter a line to store in the file: ";
   getline(cin, rec);
   fout << rec << "\n";
   cout << "\nThe line you entered was successfully saved!\n";
   fout.close();                       // close the file stream associated with "fout"

   fin.open(fname, ios::in);           // open the file for reading
   if (!fin)
   {
      cout << "Error opening the file!\n";
      return 0;
   }
   getline(fin, rec);
   cout << "\nThe file contains:\n";
   cout << rec;
   fin.close();                        // close the file stream associated with "fin"

   cout << endl;
   return 0;
}

The following snapshot shows the initial output produced by the above program:

c++ opening and closing a file example

Now, type the file's name, such as "fresherearth.txt," and press the ENTER key to open it. If the file already exists, it will be opened in editing mode. Furthermore, any content that was previously available in the pre-existing file will be deleted. If the specified file does not exist, a new file with the specified name will be created in the current directory. The current directory refers to the location of the C++ source code. The screenshot below shows the sample run with "fresherearth.txt" as the file name and "Hello there, is everything alright?" as the line of text to store in it.

Open and close file example program in C++

More Examples

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

C++ Quiz


« Previous Tutorial Next Tutorial »