Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7050403
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T03:08:20+00:00 2026-05-28T03:08:20+00:00

I am using fid = fopen(‘fgfg.txt’); to open a file. Sometimes an error occurs

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T03:08:21+00:00Added an answer on May 28, 2026 at 3:08 am

    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
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm using fmemopen to create a variable FILE* fid to pass it to a
Using ASIHTTPRequest, I downloaded a zip file containing a folder with several audio files.
I opened a File in Matlab using the a+ permission to read and write,
I have a .txt file with the following data: sampleF.txt --> (tab delimited) MSFT
I'm using jQuery DataTable to form a table out of this data.txt: { aaData
I'm using code that someone else wrote to load a file format that I
I'm using a MYSQL database. I have the following: tbl1 ID(p) | FID(p) 1
I have created a binary file using the following matlab code: x is an
I'm using http://aquantum-demo.appspot.com/file-upload to upload files to my site. The file uploads fine in
I am using textscan to read data from a file. The data being read

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.