Search code examples
c++file-ioerror-handlingofstream

Can you safely close a file that was never opened?


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.


Solution

  • 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.