IO Errors

Steinitz, Dominic J Dominic.J.Steinitz@BritishAirways.com
25 May 2001 10:35:06 Z


Can anyone tell me why this behaves as it does? In Hugs, I get 

C:\My Documents\functional\ldapsck1\buffer.hs
Main> main

Illegal operation
(561 reductions, 1029 cells)
Main>

If the input file is the one line:

1234567812345678

the output file is:

Starting logging
1234567812345678
Error

In ghc, the program hangs without even creating a file.

Dominic

import IO

main :: IO ()
main = 
   do ofh <- openFile "log.txt" WriteMode
      logMessage ofh "Starting logging"
      ifh <- openFile "tst.txt" ReadMode
      let loop = do b <- try (getBuffer ifh 16)
                    case b of
                       Right msg ->
                         do logMessage ofh msg
                            loop
                       Left e ->
                          if isEOFError e
                             then do logMessage ofh "Finishing logging"
                                     hClose ofh
                             else do logMessage ofh "Error"
                                     ioError e
         in loop         

logMessage :: Handle -> String -> IO ()
logMessage hd msg =
   do hPutStrLn hd msg
      hFlush hd

getBuffer :: Handle -> Int -> IO String
getBuffer h n =
   if (n <= 0)
      then return ""
      else do c <- hGetChar h
              cs <- getBuffer h (n-1)
              return (c:cs)

-------------------------------------------------------------------------------------------------
21st century air travel     http://www.britishairways.com