3
votes

According to C++17 the 2nd parameter of some of the constructors and the open functions for the fstream, ifstream, and ofstream classes represents the mode in which the file is to be opened. Those parameters are, respectively:

ios_base::openmode mode = ios_base::in | ios_base::out
ios_base::openmode mode = ios_base::in
ios_base::openmode mode = ios_base::out

I've read several different seemingly contradictory things on the Internet and in C++ books about the non-default behavior of the mode parameter, especially for fstream, and I can't find anything I can decipher in the standard itself regarding it. Below are some of the things I've read and I'd like to get a clarification regarding them, especially the non-default behaviors, with references to the standard if possible:

fstream:

  1. There is no default mode. -- This clearly seems to be wrong based upon the above.
  2. The default mode is ios_base::in | ios_base::out only if the mode argument is omitted completely. If it is supplied the mode is determined only by the flags that are actually specified in that argument.

ifstream:

The default mode is ios_base::in. If a mode argument is provided its flags will be OR'd with ios_base::in.

ofstream:

The default mode is ios_base::out. If a mode argument is provided its flags will be OR'd with ios_base::out.

Finally, although I can easily find the meanings of all of the flags defined in books and online, I can't find their meanings clearly defined in the standard itself - just examples showing them being used. Is there a table of some kind or something equivalent in the standard that consolidates them?

Thanks, Ray

1
The standard defines the open modes in terms of the C open modes. Digging a bit more to see if I can find the rest for you before someone who's memorized the standard gets you a complete answer.user4581301

1 Answers

4
votes
explicit basic_ifstream(const char* s, ios_base::openmode mode = ios_base::in);

[ifstream.cons]/2 Constructs an object of class basic_­ifstream<charT, traits> ... then calls rdbuf()->open(s, mode | ios_­base::in)

Similarly, [ofstream.cons]/2 mentions mode | ios_base::out for basic_ofstream. However, fstream constructor passes the mode straight through:

[fstream.cons]/2 ... Then calls rdbuf()->open(s, mode)

The meaning of mode is defined by this table in [filebuf.members], in terms of mode string passed to fopen from C standard library. The meaning of that, in turn, is defined in the C standard.