Search code examples
matlabdelete-file

How to delete temporary files in MATLAB


I have a MATLAB script that needs to write temporary files to disk, and then delete these files when I'm done with them. It's important that I delete the files myself (rather than letting them accumulate in the temp directory) because the code in question is in a loop that executes many times. If the files aren't promptly deleted, the script will quickly gobble up large amounts of disk space.

I thought that the code snippet below would work, and it does when I run it on its own. For some reason, though, the snippet fails when I include it in my larger script. The temporary files don't get deleted and clutter up the temp directory.

    % create temporary file
    myTmpFile = [tempname '.wav'];
    fs = 32000;
    wavwrite(zeros(fs,1),fs,myTmpFile);
    

    % use the file here
 

    % delete the file when we're done
    prevState = recycle('off'); % turn recycle off to permanently delete files
    delete(myTmpFile)
    recycle(prevState);         % restore the state of recycle

Does anyone have any idea what I'm doing wrong? I'm running MATLAB 7.10.0 on OS X 10.7.3.


Solution

  • I figured it out. It turns out the problem wasn't in the snippet above; it was in a completely different section of my code. I was writing temp files elsewhere and had forgotten to delete them.

    Bottom line: there's absolutely nothing wrong with the snippet above. tempname, recycle and delete are perfectly good functions for creating and destroying temporary files.