liveBook · Manning

hClose

As explained in Learn Haskell by Example

hClose is a Haskell System.IO function that closes a Handle and completes pending buffered output.

hClose is a System.IO action that closes a Handle. Closing flushes pending buffered output and releases the handle, so handles should not remain open longer than needed. section 14.1.1 section 14.1.2

Write, close, and read a file

In GHCi, open a file in WriteMode, write a line with hPutStrLn, and call hClose before reopening it in ReadMode. Close the reading handle as well. Keeping both handles open can cause a resource-busy exception. section 14.1.1

Use hClose deliberately when working with file handles:

  • Close a writing handle to flush data that may still be in its buffer. section 14.1.2
  • Avoid relying on garbage collection to close handles; its timing is uncertain and another handle may be opened first. section 14.2
  • Remember that an exception before hClose creates a resource-acquisition and release problem. section 14.2
ghci> import System.IO
ghci> h <- openFile "test.txt" WriteMode
ghci> hPutStrLn h "Hello World"
ghci> hClose h
ghci> h2 <- openFile "test.txt" ReadMode
ghci> hGetLine h2
"Hello World"
ghci> hClose h2

Follow the complete GHCi interaction for writing, closing, reopening, reading, and closing a file. section 14.1.1

How Learn Haskell by Example covers it

How deep it goes
Explains closure, buffer flushing, handle conflicts, garbage collection, and exception risks, but stops short of a safe release pattern.
Examples
Demonstrates GHCi file writing and reading, a locked dual-handle failure, and an insecure file-type reader.
What it assumes
Assumes familiarity with Handle and file modes while introducing explicit closure, buffering, and resource-release concerns.
What you can do after
Operate file handles by closing them after use and recognizing buffering, locking, and exception-related risks.
How it connects
Connects hClose with Handle, openFile, hPutStrLn, hFlush, buffering, garbage collection, and resource acquisition and release.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.