3
votes

I call a function (containing fopen and fclose) from the Command Window and then after MATLAB encounters an error that I fix (the runtime of the program stops after I save my corrections), I want to delete the file it created, in order to repeat the process. However, MATLAB, somehow, still has the file open and typing in fclose(f), in the Command Window does not make MATLAB let go of the file.

function something(something)
    f = fopen('something.txt', 'w');        
    %statments with fprintf  
    fclose(f);    
end
2

2 Answers

5
votes

You may not have access to the handle f from outside the function, in which case you can try fclose('all') from the Matlab command window.

Generally it is best practice to use a try .. catch ... statement around code that uses a file, so that you always call fclose and release the handle if an error occurs.

If you are still unable to delete the file, and assuming it is not locked by another process (for example if you are viewing it externally in Windows Notepad), it may be that you are calling library functions from Matlab and that the shared library maintains the file lock. In this case, try reloading the library using the unloadlibrary and loadlibrary commands.

0
votes

Using an onCleanup object can be very useful in this case.

Here's your code rewritten to use onCleanup - the fclose will now get called when the function terminates whether normally, or because of an error.

function something(something)
    f = fopen('something.txt', 'w');        
    closer = onCleanup( @()fclose(f) );
    % statements with fprintf 
end

The documentation also includes an example for exactly this case.