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

Re: filename check

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
; 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


Craig B. Markwardt, Ph.D.         EMAIL:    craigmnet@cow.physics.wisc.edu
Astrophysics, IDL, Finance, Derivatives | Remove "net" for better response