user429400
user429400

Reputation: 3325

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

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

Upvotes: 7

Views: 2239

Answers (4)

bjskishore123
bjskishore123

Reputation: 6342

If you are using C function for file open, you can use _fcloseall function for closing all the opened files.

If you are using C++, Like James suggested, stream destructor should take care of it.

Upvotes: 1

Kristopher Johnson
Kristopher Johnson

Reputation: 82535

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

Upvotes: 2

James McNellis
James McNellis

Reputation: 355049

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").

Upvotes: 7

Falcon
Falcon

Reputation: 3160

Which environment are you in? You can always check the file descriptors opened by the process and close them forcefully.

Under linux you can use the lsof command to list open files for a process. Do it once before the method and once after the method to detect newly opened files. Hopefully you aren't fighting some multithreaded legacy beast.

Upvotes: 0

Related Questions