13

If I have a std::ofstream that may or may not have been opened, is it safe to try to close regardless? In otherwords does close() do anything nasty (throw exception, etc) if !is_open(). For example

std::ofstream out;
if (some_condition)
{
    out.open(path, std::ios::out);
}

After I'm done with the file, can I just say

out.close();

Or should I first check

if (out.is_open())
    out.close();

The only description of std::basic_fstream::close on cppreference is

Closes the associated file.
Effectively calls rdbuf()->close(). If an error occurs during operation, setstate(failbit) is called.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 2
    You could just let the object go out of scope ... – Sebastian Redl Oct 09 '15 at 16:20
  • 1
    Generally that is what I do, which is why I like `std::ofstream`, but in this particular case I would like the file to be closed earlier than it would otherwise be. – Cory Kramer Oct 09 '15 at 16:21
  • 2
    If you look on cppreference for [`std::ofstream::close`](http://www.cplusplus.com/reference/fstream/ofstream/close/), you will see that the specific example of calling `close` on a not opened file is used. In summary, nothing nasty occurs, it just sets the failbit so anything you try to do with the `ofstream` afterwards might cause issues. – R_Kapp Oct 09 '15 at 16:25
  • 3
    @R_Kapp that's not cppreference – Cubbi Oct 09 '15 at 16:57
  • @Cubbi: ... Where's my coffee? – R_Kapp Oct 09 '15 at 16:58
  • cppreference now links that rdbuf->close to the filebuf close page, which is a lot more detailed – Cubbi Oct 09 '15 at 18:25

3 Answers3

13

It does exactly what cppreference says it will: the failbit will be set, and you can inspect it with the fail() method. For instance, the following prints "fail\n":

#include <iostream>
#include <fstream>
int main(int argc, char ** argv)
{
        std::ofstream out;
        out.close();
        if (out.fail())
                std::cout << "fail" << std::endl;
        return 0;
}

In terms of interaction with the operating system, there's nothing there to close, but it's otherwise harmless.

Gary Jackson
  • 565
  • 4
  • 18
8

From the C++ standard, §27.9.1.4 [filebuf.members], paragraph 6:

basic_filebuf<charT,traits>* close();
   Effects: If is_open() == false, returns a null pointer.…

rici
  • 234,347
  • 28
  • 237
  • 341
6

Yes, you can close() the file always, even the file is not opened. No matter LINUX or Windows, I always close() without thinking they are opened or not.

From LINUX:

void
close()
{
     if (!_M_filebuf.close())
        this->setstate(ios_base::failbit);
}
edmz
  • 8,220
  • 2
  • 26
  • 45