help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Detecting if a file is open


From: gOS
Subject: Re: Detecting if a file is open
Date: Mon, 2 Jun 2008 06:17:52 -0700 (PDT)

Let me give you a specific example:

function = foo(bar.txt)

try
   fid = fopen(bar.txt)
   if(fid < 0)
      warning('file never opened)
      return;
   end

   % do a bunch of stuff with the file

   % ! an unforeseen error occurs here %

   % do more stuff with the file

   fclose(fid)

catch

  % detect whether the file is still open (see original post)

  if ( fileIsOpen )
     fclose(fid)
  end
end

%%%%%%%%%%%End Example%%%%%%%%%%%%%%%%%%%%%%

The point is that if you never close fid with fclose, then the file remains
opened after the function terminates. I assume that this is normal, expected
behavior for Octave, but it is always wise to clean up resources when you
are done using them. If you never call fclose, you can't access the file
again in Octave, using windows explorer, or any other interface, until you
close octave and then restart it.

So quite simply, I'm trying to detect whether octave still maintains control
of a file or if it has closed it. If the error occurs after the fclose,
there is no point to close it again, especially as this will throw another
error.

After calling fopen, fid retains its value regardless of whether the file
has been closed or not. So fid is not a reliable indicator as to whether the
file is open or not.

Does this make more sense now?











gOS wrote:
> 
> I'm wondering if there is a better way to do this.
> 
> fid = fopen('testfile.txt','w')
> 
> if(exist('fid'))
>    if(isequal(ferror(fid),''))
>      fclose(fid);
>    end
> end
> 
> essenially, I'm assuming that if ferror is an empty string, then the file
> needs closed. I'm using try catch error handling, and just want to make
> sure everything is cleaned up properly before I exit the specific
> function. This is useful when you want to work with a file without having
> to completely shut down octave and restart it.
> 
> Is there a method that is more often used to tell if a file is open?
> Perhaps more reliably? I just played around until I found this.
> 

-- 
View this message in context: 
http://www.nabble.com/Detecting-if-a-file-is-open-tp17566839p17601068.html
Sent from the Octave - General mailing list archive at Nabble.com.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]