Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make sure that a file will be closed at the end of the run

Tags:

c++

Suppose someone wrote a method that opens a certain file and forgets to close it in some cases. Given this method, can I make sure that the file is closed without changing the code of the original method?

The only option I see is to write a method that wraps the original method, but this is only possible if the file is defined outside the original method, right? Otherwise it's lost forever...

like image 251
user429400 Avatar asked Sep 06 '10 15:09

user429400


2 Answers

Since this is C++, I would expect that the I/O streams library (std::ifstream and friends) would be used, not the legacy C I/O library. In that case, yes, the file will be closed because the stream is closed by the stream object's destructor.

If you are using the legacy C API, then no, you're out of luck.

In my opinion, the best answer to an interview question like this is to point out the real flaw in the code--managing resources manually--and to suggest the correct solution: use automatic resource management ("Resource Acquisition is Initialization" or "Scope-Bound Resource Management").

like image 120
James McNellis Avatar answered Oct 05 '22 23:10

James McNellis


You are correct that if the wrapper doesn't somehow get a reference to the opened file, it may be difficult to close it. However, the operating system might provide a means to get a list of open files, and you could then find the one you need to close.

However, note that most (practically all) operating systems take care of closing files when the application exits, so you don't need to worry about a file being left open indefinitely after the program stops. (This may or may not be a reasonable answer to the question you were given, which seems incredibly vague and ambiguous.)

like image 34
Kristopher Johnson Avatar answered Oct 06 '22 01:10

Kristopher Johnson