My code creates files, uses them and then deletes them. The deletion part does not always work

3 views (last 30 days)
Iddo Weiner
Iddo Weiner on 26 Sep 2017
Edited: Jan on 26 Sep 2017
My code is built in a way that data files and folders are created, used and then deleted.
I've noticed that every now and then the deletion part doesn't work. It's strange becasue if I run the same task many times in a loop it works most of the time but every now and then it doesn't (with the same data). So, I suspect the problem has to do with the way MATLAB is configured on my PC, and maybe something that has to do with permissions (?).
The actual code for deletion is simple:
delete output.txt
rmdir(results_dir, 's')
I also tried using the windows command:
system(['rmdir /s /Q "', folder_to_delete '"'])
but the same problem occurs here too..
I'd be happy to hear some ideas :) Thanks!

Answers (2)

Stephen23 on 26 Sep 2017
Edited: Stephen23 on 26 Sep 2017
Sometimes pausing helps, because OS operations do seem to take a finite amount of time:
delete output.txt
rmdir(results_dir, 's')
I created some temporary directories filled with files (for zipping into compressed file) and found that the only reliable way to delete them was to use the time to create and copy all the files as an approximate measure of the folder complexity and call pause(2*toc) before deleting the folder. I guess it gave enough time for my (ancient) windows to catch up with itself.
  1 Comment
Iddo Weiner
Iddo Weiner on 26 Sep 2017
Thanks for the answer,
this is a good tip, but unfortunately this is not the case here.. (it doesn't solve the problem..)
When I try to manually delete this files / folders I get a prompt from my OS saying that it requires admin permissions to delete the file.. So the way I see it - MATLAB sometimes creates files with some kind of protection against deletion.. No idea why.. There's no difference between the files it decides to "protect" and all the others that get deleted just fine

Sign in to comment.

Jan on 26 Sep 2017
Edited: Jan on 26 Sep 2017
You cannot delete folders with limited user privileges, if they have been created with elevanted admin privilegs. A single file created with admin privilegs does not allow to delete the parent folder also. Therefore it is required to check the permissions of the folders and the files. Perhaps the blocking file or folder reveals more details about of the source of the problem.
Then current description "the deletion part doesn't work" is not clear enough. Please provide the error message obtained by:
[status, msg] = rmdir(results_dir, 's');
if status ~= 0
error('RMDIR Failed: %s', msg);

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!