Search code examples
c++fileiostandardsfstream

Does `ios_base::app` guarantee `ios_base::out` is implicitly specified?


A:

std::ofstream("test.txt", std::ios_base::app);

B:

std::ofstream("test.txt", std::ios_base::app|std::ios_base::out);

Does the C++ standard guarantee A is identical to B?


Solution

  • Yes, as per [ofstream.cons]

    explicit basic_ofstream(const char* s,
        ios_base::openmode mode = ios_base::out);
    

    Effects: Constructs an object of class basic_ofstream, initializing the base class with basic_ostream(&sb) and initializing sb with basic_filebuf<charT,traits>()), then calls rdbuf()->open(s, mode|ios_base::out). If that function returns a null pointer, calls setstate(failbit).

    Note that it isn't app that has this guarantee but the call to the underlying streambuf itself; any flags you pass to the constructor/open are always ored with out (and likewise with in for ifstream).