如何在Matlab中关闭文件句柄? [英] How to close file handle in matlab?

查看:432
本文介绍了如何在Matlab中关闭文件句柄?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的matlab代码创建一个新文件,并在其中写入一些内容.我正在使用fclose()释放文件句柄,但是由于某些原因,当我在程序完成执行后尝试删除创建的文件时,出现文件正在使用错误. 关闭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.

推荐答案

您可能遇到的问题是一个常见的问题,而我经常遇到的一个问题是因为它很容易遗漏...

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.

更正错误并重新运行代码后,最终会打开从中读取并关闭的 new 文件句柄,并一直保持 old 打开文件句柄仍然存在.正如 kwatford指出的,您可以看到此打开使用 FOPEN 函数处理文件.

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.

一种解决方案是仅将fclose all用作 Jacob建议,关闭每个打开的文件句柄.您还可以退出MATLAB,后者关闭旧文件句柄,让我们删除文件.当您重新启动MATLAB并重新运行您的代码(现在没有错误)时,文件句柄不再存在问题.

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.

这篇关于如何在Matlab中关闭文件句柄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆