When a file is opened, it must be specified how it is to be opened. This means whether to create it from new or overwrite it and whether it's text or binary, read or write and if the content is to be appended to it. This is done using one or more file mode specifiers which are single letters "r", "b", "w", "a" and + (in combination with the other letters). "r" - Opens the file for reading. This fails if the file does not exist or cannot be found. "w" - Opens the file as an empty file for writing. If the file exists, its contents are destroyed. "a" - Opens the file for writing at the end of the file (appending) without removing the EOF marker before writing new data to the file; this creates the file first if it doesn't exist. Adding + to the file mode creates three new modes:
"r+" Opens the file for both reading and writing. (The file must exist.) "w+" Opens the file as an empty file for both reading and writing. If the file exists, its contents are destroyed.
"a+" Opens the file for reading and appending; the appending operation includes the removal of the EOF marker before new data is written to the file and the EOF marker is restored after writing is complete; creates the file first if it doesn't exist.

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:

 

Mode

Description

ios::ate

Write all output to the end of file (even if file position pointer is moved with seekp)

ios::app

Open a file for output and move to the end of the existing data (normally used to append data to a file, but data can be written anywhere in the file

ios::in

The original file (if it exists) will not be truncated

ios::out

Open a file for output (default for ofstream objects)

ios::trunc

Discard the file's contents if it exists (this is also the default action for ios::out, if ios::ate, ios::app, or ios::in are not specified)

ios::binary

Opens the file in binary mode (the default is text mode)

ios::nocreate

Open fails if the file does not exist

ios::noreplace

Open files if the file already exists.