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;
is.open("foo.txt", std::ios::in | std::ios::binary);

ifstream::open adds ios::in to the mode you pass, and ofstream::open adds ios::out. fstream::open does not add those flags. If you pass a mode to an fstream, include every flag you need.

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. By itself, out also truncates; in or app suppresses that.
trunc truncate Output Removes the contents of the file when opening.
ate at end Input/Output Seeks to the end of the file immediately after 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:

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



Table Of Contents