handle句柄 matlab_如何在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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值