Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 648
Cory Kramer Avatar asked Oct 09 '15 16:10

Cory Kramer


People also ask

What happens if you leave a program without closing open write files?

If you write to a file without closing, the data won't make it to the target file.

Why is it advisable to close all open files after the operation is done?

You've learned why it's important to close files in Python. Because files are limited resources managed by the operating system, making sure files are closed after use will protect against hard-to-debug issues like running out of file handles or experiencing corrupted data.

What could happen if you do not close your file after working with it in C ++?

In a large program, which runs on long after you have finished reading/writing to the file, not closing it means that your program is still holding the resource. This means that other processes cannot acquire that file until your program terminates (which may not be what you wish for).

What happens if you don't Fclose?

▪︎when a file was not closed correctly before the program is terminated normally, the operating system will try to close the file. In many cases this can prevent a data loss. ▪︎when a file was not closed correctly, and the programm is terminated unexpectedly by a crash, the loss of data can hardly be prevented.


2 Answers

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.

like image 104
Gary Jackson Avatar answered Sep 25 '22 06:09

Gary Jackson


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

like image 22
rici Avatar answered Sep 24 '22 06:09

rici