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.
(http://hackage.haskell.org/packages/archive/haskell98/latest/doc/html/IO.ht
ml#v:hGetContents)

        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
outliers.

With less pitfalls I would recommend using getContents where possible.

Chris

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

Hello,

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?

Thanks.

_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe at haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe




More information about the Haskell-Cafe mailing list