File Modes - Reading and Writing Files

In order to open a file with a stream object  open() member function is used.
open (filename, mode);
Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:


ios::in

Open for input operations.

ios::out

Open for output operations.

ios::binary

Open in binary mode.

ios::ate

Set the initial position at the end of the file.
If this flag is not set to any value, the initial position is the beginning of the file.

ios::app

All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.

ios::trunc

If the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.

ios::nocreate

Open fails if the file does not exist

ios::noreplace

Open files if the file already exists.


1. Opening a file in ios::out mode also opens it in the ios::trunk mode by default.
2. Both ios: :app and ios::ate take the control to the end of the file when it is opened. The difference between the two parameters is that the ios : : app allows the user to add data to the end of the file only, while ios : : ate mode permits the user to add data or to modify the existing data anywhere in the file. In both the cases, a file is created by the specified name, if it does not exist.
3. The parameter ios: :app can be used only with the files capable of output.
4. Creating a stream using ifstream implies input and creating a stream using ofstream implies output. So in these cases it is not necessary to provide the mode parameters.
5. The fstream class does not provide a mode by default and therefore, the mode must be provided explicitly when using an object of fstream class.
6. The mode can combine two or more parameters using the bitwise OR operator shown as follows:

      fout.open (“data”, ios: :app | ios : : nocreate)

This opens the file in the append mode but fails to open the file if it does not exist.