Search code examples
c++c++11standardsfile-handlingiostream

Does std::ofstream guarantee the old open file will be closed if opening new one?


#include <fstream>

int main()
{
    auto fout = std::ofstream("/tmp/a.txt");
    fout.open("/tmp/b.txt"); // Will "/tmp/a.txt" be closed?
    fout.open("/tmp/c.txt"); // Will "/tmp/b.txt" be closed?
}

Does std::ofstream guarantee the old open file will be closed if opening new one?


Solution

  • The second and subsequent calls will fail.

    [filebuf.members]
    basic_filebuf* open(const char* s, ios_base::openmode mode);
    2 Effects: If is_open() != false, returns a null pointer. Otherwise...

    [ofstream.members]
    void open(const char* s, ios_base::openmode mode = ios_base::out);
    3 Effects: Calls rdbuf()->open(s, mode | ios_base::out). If that function does not return a null pointer calls clear(), otherwise calls setstate(failbit)