Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

matlab - How can I close files that are left open after an error?

I am using

fid = fopen('fgfg.txt');

to open a file.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all, you can use the command

fclose all

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

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.

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

myObj.method()

and in that way:

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

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

So now you have safe handles that automatically close the file whether you lost scope of it or an error happened.

Use it like this:

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

And no need to close.

Edit: 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): 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...