C++ File I/O Opening modes


When creating a file stream, you can specify an opening mode. An opening mode is basically a setting to control how the stream opens the file.

(All modes can be found in the std::ios namespace.)

An opening mode can be provided as second parameter to the constructor of a file stream or to its open() member function:

std::ofstream os("foo.txt", std::ios::out | std::ios::trunc);

std::ifstream is;
is.open("foo.txt", std::ios::in | std::ios::binary);

It is to be noted that you have to set ios::in or ios::out if you want to set other flags as they are not implicitly set by the iostream members although they have a correct default value.

If you don't specify an opening mode, then the following default modes are used:

  • ifstream - in
  • ofstream - out
  • fstream - in and out

The file opening modes that you may specify by design are:

appappendOutputAppends data at the end of the file.
binarybinaryInput/OutputInput and output is done in binary.
ininputInputOpens the file for reading.
outoutputOutputOpens the file for writing.
trunctruncateInput/OutputRemoves contents of the file when opening.
ateat endInputGoes to the end of the file when opening.

Note: Setting the binary mode lets the data be read/written exactly as-is; not setting it enables the translation of the newline '\n' character to/from a platform specific end of line sequence.

For example on Windows the end of line sequence is CRLF ("\r\n").
Write: "\n" => "\r\n"
Read: "\r\n" => "\n"