withFile package:base

The computation withFile path mode action opens the file and runs action with the obtained handle before closing the file. Even when an exception is raised within the action, the file will still be closed. This is why withFile path mode act is preferable to
openFile path mode >>= (\hdl -> act hdl >>= hClose hdl)
See also: bracket
withFile name mode act opens a file like openFile and passes the resulting handle to the computation act. The handle will be closed on exit from withFile, whether by normal termination or by raising an exception. If closing the handle raises an exception, then this exception will be raised by withFile rather than any exception raised by act.
withFileBlocking name mode act opens a file like openFileBlocking and passes the resulting handle to the computation act. The handle will be closed on exit from withFileBlocking, whether by normal termination or by raising an exception. If closing the handle raises an exception, then this exception will be raised by withFile rather than any exception raised by act.