When I open a file for reading in Haskell, I\'ve found that I can\'t use the contents of the file after closing it. For example, this program will print the contents of a file:<
As previously noted, hGetContents
is lazy. readFile
is strict, and closes the file when it's done:
main = do contents <- readFile "foo"
putStr contents
yields the following in Hugs
> main
blahblahblah
where foo
is
blahblahblah
Interestingly, seq
will only guarantee that some portion of the input is read, not all of it:
main = do inFile <- openFile "foo" ReadMode
contents <- hGetContents $! inFile
contents `seq` hClose inFile
putStr contents
yields
> main
b
A good resource is: Making Haskell programs faster and smaller: hGetContents, hClose, readFile