URGENT: File exists

Richard Uhtenwoldt greon@best.com
Sat, 03 Nov 2001 07:53:28 -0800


bracaman@box.sk writes:

>I am trying to emulate bash in haskell, and i got a function called shell that waits fot the command and then executes it. The problem is that if the file does not exist, the program returns to Main (it gets out of the shell). The only thing i want to do is to return to the shell after  an IOError. 
>
>How can i perform such a thing?


You could test if the file exists, like you said before, but that test
would fail once in a while, when another process deletes the file after
your test but before the file is opened.  This is called a "race condition"
and should be avoided when possible.

The best thing is to use catch which has the type IO a -> (IOError -> IO
a) -> IO a.  An example (untested code) is

catch
  (do 
    hdl<-openFile "/home/bracaman/foo" ReadMode 
    char<-hGetChar hdl
    string<-hGetLine hdl )
  --we caught an exception:
  (\errorCode->
    if isDoesNotExistError errorCode then "return to shell" else
    if isPermissionError errorCode then "return to shell" else
    --something strange happened.
    --re-raise the exception, which will probably return control to Main.
    ioError errorCode )

P.S.
Instead of 

  (do 
    hdl<-openFile "/home/bracaman/foo" ReadMode 
    char<-hGetChar hdl
    string<-hGetLine hdl
    ... )

you could have 

  (do
    fileContentsAsABigString<-readFile "/home/bracaman/foo"
    ... )

but I try to stay away from readFile and getContents because they're
not referentially transparent.