Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close file handle in matlab?

Tags:

file

matlab

My matlab code creates a new file and writes some stuff in it. I am using fclose() to release the file handle but for some reasons when I try to delete the created file after the program has completed execution, I get a file in use error. The file can be deleted once i close matlab.

The problem is not permanent. I tried the same thing again without any changes and it works.

like image 491
meraj Avatar asked Mar 07 '11 16:03

meraj


2 Answers

I've had this problem so, so many times. Instead of closing MATLAB you can just type fclose all.

Most of the time I use fclose all in my programs --- yes, I know that closes all files opened by MATLAB but sometimes in my application, that's OK. Consider this answer as a recommendation and not a complete solution.

like image 150
Jacob Avatar answered Oct 20 '22 04:10

Jacob


The likely problem you're having is a common one, and one that I get caught by often because it's an easy one to miss...

Let's say you have a function or script that opens a file, reads some data from it, then closes the file again:

...
fid = fopen(fileName,'r');
%# Load your data here
fclose(fid);
...

Now, the first time you run the above code you may discover you've made an error in how you load the data (no one's perfect, after all). When that error occurs, the function/script will exit, neglecting to perform any code coming after the line that errors (like the call to FCLOSE). This means you still have an open file handle.

When you correct your error and re-run your code, you end up opening a new file handle that you read from and then close, and all the while the old open file handle is still there. As kwatford points out, you can see this open file handle using the FOPEN function.

One solution is to just use fclose all as Jacob suggests, closing every open file handle. You can also quit MATLAB, which closes the old file handle and let's you delete your file. When you restart MATLAB and re-run your (now error-free) code, you no longer have a problem with lingering file handles.

I discuss a more fault-tolerant way to deal with file IO in my answer to a related SO question: How do you handle resources in MATLAB in an exception safe manner? My answer there shows how onCLeanup objects can help you automatically close files that are opened in a function, whether that function exits normally or due to an error. This approach can help you avoid the problem of lingering open file handles.

like image 43
gnovice Avatar answered Oct 20 '22 05:10

gnovice