如何关闭出错后保持打开状态的文件? [英] How can I close files that are left open after an error?

查看:21
本文介绍了如何关闭出错后保持打开状态的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用

fid = fopen('fgfg.txt');

打开一个文件.

有时在我设法关闭文件之前会发生错误.在关闭 Matlab 之前,我无法对该文件进行任何操作.

Sometimes an error occurs before I manage to close the file. I can't do anything with that file until I close Matlab.

如果发生错误,我如何关闭文件?

How can I close a file if an error occurs?

推荐答案

首先可以使用命令

fclose all

其次,您可以使用 try-catch 块并关闭文件句柄

Secondly, you can use try-catch blocks and close your file handles

 try
     f = fopen('myfile.txt','r')
     % do something
     fclose(f);
 catch me
     fclose(f);
     rethrow(me);
 end

还有第三种方法,它要好得多.Matlab 现在是一种带有垃圾收集器的面向对象语言.您可以定义一个包装器对象,它将自动处理其生命周期.

There is a third approach, which is much better. Matlab is now an object-oriented language with garbage collector. You can define a wrapper object that will take care of its lifecycle automatically.

因为在 Matlab 中可以以这种方式调用对象方法:

Since it is possible in Matlab to call object methods both in this way:

myObj.method()

myObj.method()

以这种方式:

方法(myObj)

您可以定义一个类来模拟所有相关的文件命令,并封装生命周期.

You can define a class that mimics all of the relevant file command, and encapsulates the lifecycle.

classdef safefopen < handle
    properties(Access=private)
        fid;
    end

    methods(Access=public)
        function this = safefopen(fileName,varargin)            
            this.fid = fopen(fileName,varargin{:});
        end

        function fwrite(this,varargin)
            fwrite(this.fid,varargin{:});
        end

        function fprintf(this,varargin)
            fprintf(this.fid,varargin{:});
        end

        function delete(this)
            fclose(this.fid);
        end
    end

end

delete 运算符由 Matlab 自动调用.(您需要包装更多功能(fread、fseek 等)).

The delete operator is called automatically by Matlab. (There are more functions that you will need to wrap, (fread, fseek, etc..)).

所以现在您有了安全句柄,无论您丢失文件范围还是发生错误,都可以自动关闭文件.

像这样使用它:

f = safefopen('myFile.txt','wt')
fprintf(f,'Hello world!');

而且不需要关闭.

我只是想包装 fclose() 什么都不做.它可能对向后兼容性很有用 - 对于使用文件 ID 的旧函数.

I just thought about wrapping fclose() to do nothing. It might be useful for backward compatibility - for old functions that use file ids.

Edit(2): 按照@AndrewJanke 的好评,我想通过在 fclose()

Edit(2): Following @AndrewJanke good comment, I would like to improve the delete method by throwing errors on fclose()

    function delete(this)          
        [msg,errorId] = fclose(this.fid);
        if errorId~=0
            throw(MException('safefopen:ErrorInIO',msg));
        end
    end

这篇关于如何关闭出错后保持打开状态的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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