[Haskell-cafe] readFile and closing a file

Henning Thielemann lemming at henning-thielemann.de
Mon Sep 22 05:24:20 EDT 2008


On Wed, 17 Sep 2008, Mitchell, Neil wrote:

> I tend to use openFile, hGetContents, hClose - your initial readFile
> like call should be openFile/hGetContents, which gives you a lazy
> stream, and on a parse error call hClose.

I could use a function like
   withReadFile :: FilePath -> (Handle -> IO a) -> IO a
   withReadFile name action = bracket openFile hClose ...

Then, if 'action' fails, the file can be properly closed. However, there 
is still a problem: Say, 'action' is a parser which produces a data 
structure lazily. Then further processing of that data structure of type 
'a' may again stop before completing the whole structure, which would also 
leave the file open. We have to force users to do all processing within 
'action' and to only return strict values. But how to do this?


More information about the Haskell-Cafe mailing list