title: Haskell IO and closing files
body: <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>