3
#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?

xmllmx
  • 39,765
  • 26
  • 162
  • 323
  • 1
    I don't see any explicit specification of the behavior. `ofstream::open` essentially passes the `open` call onto its raw device buffer. The [documentation](https://en.cppreference.com/w/cpp/io/basic_filebuf/open) for that is not specific about what happens if a _different_ file is already open, nor what should happen if you open a file and the open fails. However, you should at least expect that _if_ a new file is opened on that object, the old one _will_ be closed, because the device buffer is responsible for managing a single resource and will not leak resources. – paddy May 10 '21 at 04:23
  • Just wanted to put this hear since you deleted your other Q. In C++20, comparisons got a major update and one of those was that `operator ==` should work both forwards and backwards. That means you don't need to write two overloads anymore when you want to have the LHS and RHS be different types. – NathanOliver May 10 '21 at 16:19

1 Answers1

3

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)

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85