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
