withFile vs. openFile

The file is being closed too early. From the documentation:

The handle will be closed on exit from withFile

This means the file will be closed as soon as the withFile function returns.

Because hGetContents and friends are lazy, it won’t try to read the file until it is forced with putStrLn, but by then, withFile would have closed the file already.

To solve the problem, pass the whole thing to withFile:

main = withFile "test.txt" ReadMode $ \handle -> do
           xs <- getlines handle
           sequence_ $ map putStrLn xs

This works because by the time withFile gets around to closing the file, you would have already printed it.

Leave a Comment