2009-06-09

不怕错误的猫


-- compile with: ghc --make cat.hs
import System.IO
import System.IO.Error
import System.Environment

cat :: String -> IO ()
cat fn = do
contents <- readFile fn
putStr contents

handler :: IOError -> IO ()
handler e
| isDoesNotExistError e =
case ioeGetFileName e of
Just path -> putStrLn $ path ++ ": file not found"
Nothing -> putStrLn "Oops! File unknown."
| otherwise = ioError e

main = do args <- getArgs
if null args
then interact id
else mapM_ (\fn -> cat fn `catch` handler) args

标签:

1 Comments:

At 04:50, Anonymous live4thee said...

昨晚才想起来,这样更简洁一点:
cat fn = readFile fn >>= putStr

 

发表评论

<< Home