No subject

Thu Jul 5 12:38:43 CEST 2012

        The handle will be closed on exit from withFile, whether by normal
termination or by raising an exception.

Your program is effectively this one

main' :: IO ()
main' = do
      h <- openFile "a.txt" ReadMode
      c <- hGetContents h
      hClose h
      putStrLn c

Now we need to check what value c has in this situation. It is actually
dependent upon how much c has been read when the file is closed.

        Once a semi-closed handle becomes closed, the contents of the
associated list becomes fixed.

(You will need to read all of the documentation to get the context -- what
'semi-closed' means, etc.)

In the above program, none of the input has been read when h is closed so
'c' is empty.

Disconcerted? hGetContents (and getContents) are probably like no other
function you will encounter in the standard Haskell libraries. I think they
are there because it is extremely convenient for certain kinds of widely
used idioms but that convenience comes at a price. But these are Haskell

With less pitfalls I would recommend using getContents where possible.


-----Original Message-----
From: haskell-cafe-bounces at
[mailto:haskell-cafe-bounces at] On Behalf Of Bin Shi
Sent: 25 July 2012 11:00
To: haskell-cafe at
Subject: [Haskell-cafe] A Question about withFile


I wrote a simple test program as

main = do
    withFile "a.txt" ReadMode (\h -> do
        c <- hGetContents h
        putStrLn c)

then I got my expected results: I'm a.txt

but if I changed to

main = do
      c <- withFile "a.txt" ReadMode hGetContents
      putStrLn c

I got just a empty line.

Where am I wrong?


Haskell-Cafe mailing list
Haskell-Cafe at

More information about the Haskell-Cafe mailing list