Opening modes

suggest change

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;"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:

File opening modes:

Mode Meaning For Description
app append Output Appends data at the end of the file.
binary binary Input/Output Input and output is done in binary.
in input Input Opens the file for reading.
out output Output Opens the file for writing.
trunc truncate Input/Output Removes contents of the file when opening.
ate at end Input Goes 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"

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents