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

Re: filename check



Craig Markwardt wrote:
> 
> Stuart Colley <src@star.ucl.ac.uk> writes:
> > Can anyone suggest a way to check that a file exists before attempting to
> > read from it, since the error messages obtained from trying to read from a
> > non-existing file, don't make it clear that file doesn't exist.
> 
> Use the ERROR keyword to OPENR to detect an error condition quietly.
> The value returned in this keyword will be non-zero if the file could
> not be opened.  Also the !ERROR_STATE system variable will contain
> helpful information describing the error:
> 
>    NAME            STRING    'IDL_M_CNTOPNFIL'
>    MSG             STRING    'OPENR: Error opening file: snorg.'
>    SYS_MSG         STRING    'No such file or directory'
> 
> According to RSI, the error conditions in !ERROR_STATE.NAME are
> guaranteed to remain constant in future versions of IDL.  To implement
> it in practice, consider this:
> 
> get_lun, unit
> openr, unit, filename, error=err
> 
> if err NE 0 then begin
>   free_lun, unit
>   message, 'ERROR: could not open '+filename
> endif
> ; Read file ...
> 
> I tend to use GET_LUN explicitly so that the unit is guaranteed to be
> valid when it is freed.  I've nit-picked about this on the newsgroup
> before.

Seeing the word nit-pick makes me want to so here goes..... :o)

I used to do the above but now I use CATCH for even open errors, forgoing the ERROR=
keyword in the open statements:

CATCH, error_status

IF ( error_status NE 0 ) THEN BEGIN
  MESSAGE, !ERR_STRING, /CONTINUE
  FREE_LUN, lun    ; If needed
  CATCH, /CANCEL
  RETURN, failure_code
ENDIF

GET_LUN, lun   ; Craig is right. Do this!
OPENR, lun, filename

....
..
.

And if one of my nested routines returns an error, then

IF ( result NE success_code ) THEN MESSAGE, 'This routine failed!', /NONAME, /NOPRINT

which sets all the error variables and the CATCH takes over.

For some bizarre reason, despite the double use of MESSAGE in the second example, error
handling this way makes me feel all warm and fuzzy on the inside coz I only have two exit
points - the bad one and the good one. Yay.

O.k. so it's not really a nit-pick, but what the hell.  :o)


paulv

-- 
Paul van Delst           Ph:  (301) 763-8000 x7274
CIMSS @ NOAA/NCEP        Fax: (301) 763-8545
Rm.202, 5200 Auth Rd.    Email: pvandelst@ncep.noaa.gov
Camp Springs MD 20746