<p>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:</p>

<pre><code>main = do inFile &lt;- openFile "foo" ReadMode
          contents &lt;- hGetContents inFile
          putStr contents
          hClose inFile
</code></pre>

<p>I expected that interchanging the <code>putStr</code> line with the <code>hClose</code> line would have no effect, but this program prints nothing:</p>

<pre><code>main = do inFile &lt;- openFile "foo" ReadMode
          contents &lt;- hGetContents inFile
          hClose inFile
          putStr contents
</code></pre>

<p>Why does this happen? I'm guessing it has something to do with lazy evaluation, but I thought these expressions would get sequenced so there wouldn't be a problem. How would you implement a function like <code>readFile</code>?</p>

The explanation is rather long to be included here. Forgive me for dispensing a short tip only: you need to read about "semi-closed file handles" and "unsafePerformIO".
In short - this behaviour is a design compromise between a semantic clearness and lazy evaluation. You should either postpone hClose until you are absolutely sure you woudnt be doing anything with the file content (like, call it in error handler, or somesuch), or use something else besides hGetContents to get file contents non-lazily.