在desugared代码中关闭句柄

时间:2015-03-20 19:55:38

标签: haskell

如果我不关闭两个手柄但是为了安全,我是如何在脱离的Real World Haskell示例中这样做

import System.IO
import Data.Char(toUpper)

main :: IO ()
main = do 
       inh <- openFile "input.txt" ReadMode
       outh <- openFile "output.txt" WriteMode
       mainloop inh outh
       hClose inh
       hClose outh

mainloop :: Handle -> Handle -> IO ()
mainloop inh outh = 
    do ineof <- hIsEOF inh
       if ineof
           then return ()
           else do inpStr <- hGetLine inh
                   hPutStrLn outh (map toUpper inpStr)
                   mainloop inh outh

capitalize = openFile "input.txt" ReadMode >>=
             \x -> hGetContents x >>=
             \y -> openFile "output2.txt" WriteMode >>=
             \z -> hPutStrLn z (fmap toUpper y)

除了“output2.txt”文件外,一切都有效,每行末尾都有^M个字符。

1 个答案:

答案 0 :(得分:1)

你只是在快乐路径中关闭手柄。您必须使用withFilebracket,以便即使抛出异常也会关闭句柄。

例如:

capitalize = withFile "input.txt" ReadMode $
             \x -> hGetContents x >>=
             \y -> withFile "output2.txt" WriteMode $
             \z -> hPutStrLn z (fmap toUpper y)

没有withFile

capitalize = openFile "input.txt" ReadMode >>=
             \x -> hGetContents x >>=
             \y -> openFile "output2.txt" WriteMode >>=
             \z -> hPutStrLn z (fmap toUpper y) >>
             hClose x >>
             hClose z