Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Severing ties between Matlab and data files when programming
Date: Wed, 31 Dec 2008 17:25:03 +0000 (UTC)
Organization: The MathWorks Inc
Lines: 40
Message-ID: <gjg9tf$9tg$1@fred.mathworks.com>
References: <gjg5s2$533$1@fred.mathworks.com> <36aa9a03-e3ee-4f42-82c3-67b4c138552f@k1g2000prb.googlegroups.com> <gjg8ge$e8d$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1230744303 10160 172.30.248.37 (31 Dec 2008 17:25:03 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Wed, 31 Dec 2008 17:25:03 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 869871
Xref: news.mathworks.com comp.soft-sys.matlab:509359


"James Tursa" <aclassyguywithaknotac@hotmail.com> wrote in message <gjg8ge$e8d$1@fred.mathworks.com>...
> Rune Allnor <allnor@tele.ntnu.no> wrote in message <36aa9a03-e3ee-4f42-82c3-67b4c138552f@k1g2000prb.googlegroups.com>...
> > On 31 Des, 17:16, "Ryan Utz" <r...@al.umces.edu> wrote:
> > 
> > The file stays in OPEN mode after the routine aborts. The solution
> > is to call FCLOSE on the file handle.
> > 
> > The potential problem is how to get to the file handle. If the file
> > was opened inside a function, you might not have access to the handle
> > from the matlab workspace.
> 
> As you mention, try-catch seems like a good way to go, but FYI file handles in MATLAB are simply doubles with integer values, not pointers like in C or C++. So even if the file was opened in a function and you don't have access to the handle directly, one could just guess the handle value. MATLAB seems to start with low numbers (e.g., 3) when opening files, so you could try
> 
> fclose(1)
> fclose(2)
> fclose(3)
> fclose(4)
>    :
>  etc.
> 
> manually at the prompt until you got the file closed. Clumsy, but it should work.
> 
> James Tursa

The function "fopen" will give you the file ID of files that are open.

fid = fopen('all');

Then you can loop through each of the elements of fid to see if it's the file of your interest:

for idx = 1:length(fid)
  if strcmp(fileIWantToClose, fopen(fid(idx)))
    fclose(fid(idx));
    break;
  end
end