HORIZON HASKELLDocslts/ghc-9.10.x248f8f02026-10-05Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · 248f8f0 · 2026-10-05

Modulerebase-1.21.2Haskell2010

Rebase.GHC.IO.Handle

  • 8 types
  • 49 values
  • Packagerebase-1.21.2
  • Exports57
  • LanguageHaskell2010
  • LicenceMIT
  • SourceTypes.hs
datadata Handle
#

Haskell defines operations to read and write characters from and to files, represented by values of type Handle. Each value of this type is a handle: a record used by the Haskell run-time system to manage I/O with file system objects. A handle has at least the following properties:

  • whether it manages input or output or both;

  • whether it is open, closed or semi-closed;

  • whether the object is seekable;

  • whether buffering is disabled, or enabled on a line or block basis;

  • a buffer (whose length may be zero).

Most handles will also have a current I/O position indicating where the next input or output operation will occur. A handle is readable if it manages only input or both input and output; likewise, it is writable if it manages only output or both input and output. A handle is open when first allocated. Once it is closed it can no longer be used for either input or output, though an implementation cannot re-use its storage while references remain to it. Handles are in the Show and Eq classes. The string produced by showing a handle is system dependent; it should include enough information to identify the handle for debugging. A handle is equal according to == only to itself; no attempt is made to compare the internal state of different handles for equality.

Instances2Eq, Show
  • Eq HandleDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Handle.Types
  • Show HandleDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Handle.Types
valuehClose :: Handle -> IO ()
#

Computation hClose hdl makes handle hdl closed. Before the computation finishes, if hdl is writable its buffer is flushed as for hFlush. Performing hClose on a handle that has already been closed has no effect; doing so is not an error. All other operations on a closed handle will fail. If hClose fails for any reason, any further operations (apart from hClose) on the handle will still fail as if hdl had been successfully closed.

hClose is an interruptible operation in the sense described in Control.Exception. If hClose is interrupted by an asynchronous exception in the process of flushing its buffers, then the I/O device (e.g., file) will be closed anyway.

valuehFlush :: Handle -> IO ()
#

The action hFlush hdl causes any items buffered for output in handle hdl to be sent immediately to the operating system.

This operation may fail with:

  • isFullError if the device is full;

  • isPermissionError if a system resource limit would be exceeded. It is unspecified whether the characters in the buffer are discarded or retained under these circumstances.

valuehGetContents :: Handle -> IO String
#

Computation hGetContents hdl returns the list of characters corresponding to the unread portion of the channel or file managed by hdl, which is put into an intermediate state, semi-closed. In this state, hdl is effectively closed, but items are read from hdl on demand and accumulated in a special list returned by hGetContents hdl.

Any operation that fails because a handle is closed, also fails if a handle is semi-closed. The only exception is GHC.Internal.System.IO.hClose. A semi-closed handle becomes closed:

  • if GHC.Internal.System.IO.hClose is applied to it;

  • if an I/O error occurs when reading an item from the handle;

  • or once the entire contents of the handle has been read.

Once a semi-closed handle becomes closed, the contents of the associated list becomes fixed. The contents of this final list is only partially specified: it will contain at least all the items of the stream that were evaluated prior to the handle becoming closed.

Any I/O errors encountered while a handle is semi-closed are simply discarded.

This operation may fail with:

valuehGetLine :: Handle -> IO String
#

Computation hGetLine hdl reads a line from the file or channel managed by hdl. hGetLine does not return the newline as part of the result.

A line is separated by the newline set with GHC.Internal.System.IO.hSetNewlineMode or nativeNewline by default. The read newline character(s) are not returned as part of the result.

If hGetLine encounters end-of-file at any point while reading in the middle of a line, it is treated as a line terminator and the (partial) line is returned.

This operation may fail with:

  • isEOFError if the end of file is encountered when reading the first character of the line.

Examples
Example1 expression
withFile "/home/user/foo" ReadMode hGetLine >>= putStrLnthis is the first line of the file :O
Example1 expression
withFile "/home/user/bar" ReadMode (replicateM 3 . hGetLine)["this is the first line","this is the second line","this is the third line"]
valuehGetBuf :: Handle -> Ptr a -> Int -> IO Int
#

hGetBuf hdl buf count reads data from the handle hdl into the buffer buf until either EOF is reached or count 8-bit bytes have been read. It returns the number of bytes actually read. This may be zero if EOF was reached before any data was read (or if count is zero).

hGetBuf never raises an EOF exception, instead it returns a value smaller than count.

If the handle is a pipe or socket, and the writing end is closed, hGetBuf will behave as if EOF was reached.

hGetBuf ignores the prevailing System.IO.TextEncoding and NewlineMode on the Handle, and reads bytes directly.

datadata BufferMode
#

Three kinds of buffering are supported: line-buffering, block-buffering or no-buffering. These modes have the following effects. For output, items are written out, or flushed, from the internal buffer according to the buffer mode:

  • line-buffering: the entire output buffer is flushed whenever a newline is output, the buffer overflows, a GHC.Internal.System.IO.hFlush is issued, or the handle is closed.

  • block-buffering: the entire buffer is written out whenever it overflows, a GHC.Internal.System.IO.hFlush is issued, or the handle is closed.

  • no-buffering: output is written immediately, and never stored in the buffer.

An implementation is free to flush the buffer more frequently, but not less frequently, than specified above. The output buffer is emptied as soon as it has been written out.

Similarly, input occurs according to the buffer mode for the handle:

  • line-buffering: when the buffer for the handle is not empty, the next item is obtained from the buffer; otherwise, when the buffer is empty, characters up to and including the next newline character are read into the buffer. No characters are available until the newline character is available or the buffer is full.

  • block-buffering: when the buffer for the handle becomes empty, the next block of data is read into the buffer.

  • no-buffering: the next input item is read and returned. The GHC.Internal.System.IO.hLookAhead operation implies that even a no-buffered handle may require a one-character buffer.

The default buffering mode when a handle is opened is implementation-dependent and may depend on the file system object which is attached to that handle. For most implementations, physical files will normally be block-buffered and terminals will normally be line-buffered.

Constructors

  • NoBuffering

    buffering is disabled if possible.

  • LineBuffering

    line-buffering should be enabled if possible.

  • BlockBuffering (Maybe Int)

    block-buffering should be enabled if possible. The size of the buffer is n items if the argument is Just n and is otherwise implementation-dependent.

Instances4Eq, Ord, Read, Show
  • Eq BufferModeDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Handle.Types
  • Ord BufferModeDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Handle.Types
  • Read BufferModeDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Handle.Types
  • Show BufferModeDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Handle.Types
datadata Newline
#

The representation of a newline in the external file or stream.

Constructors

Instances4Eq, Ord, Read, Show
  • Eq NewlineDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Handle.Types
  • Ord NewlineDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Handle.Types
  • Read NewlineDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Handle.Types
  • Show NewlineDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Handle.Types
valuehDuplicate :: Handle -> IO Handle
#

Returns a duplicate of the original handle, with its own buffer. The two Handles will share a file pointer, however. The original handle's buffer is flushed, including discarding any input data, before the handle is duplicated.

valuehDuplicateTo :: Handle -> Handle -> IO ()
#

Makes the second handle a duplicate of the first handle. The second handle will be closed first, if it is not already.

This can be used to retarget the standard Handles, for example:

do h <- openFile "mystdout" WriteMode
   hDuplicateTo h stdout
valuehFlushAll :: Handle -> IO ()
#

The action hFlushAll hdl flushes all buffered data in hdl, including any buffered read data. Buffered read data is flushed by seeking the file position back to the point before the buffered data was read, and hence only works if hdl is seekable (see hIsSeekable).

This operation may fail with:

  • isFullError if the device is full;

  • isPermissionError if a system resource limit would be exceeded. It is unspecified whether the characters in the buffer are discarded or retained under these circumstances;

  • isIllegalOperation if hdl has buffered read data, and is not seekable.

valuehIsEOF :: Handle -> IO Bool
#

For a readable handle hdl, hIsEOF hdl returns True if no further input can be taken from hdl or for a physical file, if the current I/O position is equal to the length of the file. Otherwise, it returns False.

NOTE: hIsEOF may block, because it has to attempt to read from the stream to determine whether there is any more data to be read.

Is the handle connected to a terminal?

On Windows the result of hIsTerminalDevide might be misleading, because non-native terminals, such as MinTTY used in MSYS and Cygwin environments, are implemented via redirection. Use System.Win32.Types.withHandleToHANDLE System.Win32.MinTTY.isMinTTYHandle to recognise it. Also consider ansi-terminal package for crossplatform terminal support.

valuehLookAhead :: Handle -> IO Char
#

Computation hLookAhead returns the next character from the handle without removing it from the input buffer, blocking until a character is available.

This operation may fail with:

valuehSeek :: Handle -> SeekMode -> Integer -> IO ()
#

Computation hSeek hdl mode i sets the position of handle hdl depending on mode. The offset i is given in terms of 8-bit bytes.

If hdl is block- or line-buffered, then seeking to a position which is not in the current buffer will first cause any items in the output buffer to be written to the device, and then cause the input buffer to be discarded. Some handles may not be seekable (see hIsSeekable), or only support a subset of the possible positioning operations (for instance, it may only be possible to seek to the end of a tape, or to a positive offset from the beginning or current position). It is not possible to set a negative I/O position, or for a physical file, an I/O position beyond the current end-of-file.

This operation may fail with:

  • GHC.Internal.System.IO.Error.isIllegalOperationError if the Handle is not seekable, or does not support the requested seek mode.

  • isPermissionError if a system resource limit would be exceeded.

valuehSetBuffering :: Handle -> BufferMode -> IO ()
#

Computation hSetBuffering hdl mode sets the mode of buffering for handle hdl on subsequent reads and writes.

If the buffer mode is changed from BlockBuffering or LineBuffering to NoBuffering, then

  • if hdl is writable, the buffer is flushed as for hFlush;

  • if hdl is not writable, the contents of the buffer are discarded.

This operation may fail with:

  • isPermissionError if the handle has already been used for reading or writing and the implementation does not allow the buffering mode to be changed.

valuehSetEcho :: Handle -> Bool -> IO ()
#

Set the echoing status of a handle connected to a terminal.

valuehTell :: Handle -> IO Integer
#

Computation hTell hdl returns the current position of the handle hdl, as the number of bytes from the beginning of the file. The value returned may be subsequently passed to hSeek to reposition the handle to the current position.

This operation may fail with:

  • GHC.Internal.System.IO.Error.isIllegalOperationError if the Handle is not seekable.

valuehLock :: Handle -> LockMode -> IO ()
#

If a Handle references a file descriptor, attempt to lock contents of the underlying file in appropriate mode. If the file is already locked in incompatible mode, this function blocks until the lock is established. The lock is automatically released upon closing a Handle.

Things to be aware of:

1) This function may block inside a C call. If it does, in order to be able to interrupt it with asynchronous exceptions and/or for other threads to continue working, you MUST use threaded version of the runtime system.

2) The implementation uses LockFileEx on Windows and flock otherwise, hence all of their caveats also apply here.

3) On non-Windows platforms that don't support flock (e.g. Solaris) this function throws FileLockingNotImplemented. We deliberately choose to not provide fcntl based locking instead because of its broken semantics.

valuehGetBufNonBlocking :: Handle -> Ptr a -> Int -> IO Int
#

hGetBufNonBlocking hdl buf count reads data from the handle hdl into the buffer buf until either EOF is reached, or count 8-bit bytes have been read, or there is no more data available to read immediately.

hGetBufNonBlocking is identical to hGetBuf, except that it will never block waiting for data to become available, instead it returns only whatever data is available. To wait for data to arrive before calling hGetBufNonBlocking, use hWaitForInput.

If the handle is a pipe or socket, and the writing end is closed, hGetBufNonBlocking will behave as if EOF was reached.

hGetBufNonBlocking ignores the prevailing System.IO.TextEncoding and NewlineMode on the Handle, and reads bytes directly.

NOTE: on Windows, this function does not work correctly; it behaves identically to hGetBuf.

valuehGetChar :: Handle -> IO Char
#

Computation hGetChar hdl reads a character from the file or channel managed by hdl, blocking until a character is available.

This operation may fail with:

valuehPutBuf :: Handle -> Ptr a -> Int -> IO ()
#

hPutBuf hdl buf count writes count 8-bit bytes from the buffer buf to the handle hdl. It returns ().

hPutBuf ignores any text encoding that applies to the Handle, writing the bytes directly to the underlying file or device.

hPutBuf ignores the prevailing System.IO.TextEncoding and NewlineMode on the Handle, and writes bytes directly.

This operation may fail with:

  • ResourceVanished if the handle is a pipe or socket, and the reading end is closed. (If this is a POSIX system, and the program has not asked to ignore SIGPIPE, then a SIGPIPE may be delivered instead, whose default action is to terminate the program).

valuehPutChar :: Handle -> Char -> IO ()
#

Computation hPutChar hdl ch writes the character ch to the file or channel managed by hdl. Characters may be buffered if buffering is enabled for hdl.

This operation may fail with:

valuehWaitForInput :: Handle -> Int -> IO Bool
#

Computation hWaitForInput hdl t waits until input is available on handle hdl. It returns True as soon as input is available on hdl, or False if no input is available within t milliseconds. Note that hWaitForInput waits until one or more full characters are available, which means that it needs to do decoding, and hence may fail with a decoding error.

If t is less than zero, then hWaitForInput waits indefinitely.

This operation may fail with:

  • isEOFError if the end of file has been reached.

  • a decoding error, if the input begins with an invalid byte sequence in this Handle's encoding.

NOTE for GHC users: unless you use the -threaded flag, hWaitForInput hdl t where t >= 0 will block all other Haskell threads for the duration of the call. It behaves like a safe foreign call in this respect.

Use the native newline representation on both input and output

nativeNewlineMode  = NewlineMode { inputNL  = nativeNewline
                                   outputNL = nativeNewline }

Map '\r\n' into '\n' on input, and '\n' to the native newline representation on output. This mode can be used on any platform, and works with text files using any newline convention. The downside is that readFile >>= writeFile might yield a different file.

universalNewlineMode  = NewlineMode { inputNL  = CRLF,
                                      outputNL = nativeNewline }
datadata SeekMode
#

A mode that determines the effect of GHC.Internal.System.IO.hSeek hdl mode i.

Constructors

  • AbsoluteSeek

    the position of hdl is set to i.

  • RelativeSeek

    the position of hdl is set to offset i from the current position.

  • SeekFromEnd

    the position of hdl is set to offset i from the end of the file.

Instances6Enum, Eq, Ord, Read, Show, Ix
  • Enum SeekModeDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Device
  • Eq SeekModeDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Device
  • Ord SeekModeDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Device
  • Read SeekModeDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Device
  • Show SeekModeDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Device
  • Ix SeekModeDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Device
datadata NewlineMode
#

Specifies the translation, if any, of newline characters between internal Strings and the external file or stream. Haskell Strings are assumed to represent newlines with the '\n' character; the newline mode specifies how to translate '\n' on output, and what to translate into '\n' on input.

Constructors

Instances4Eq, Ord, Read, Show
  • Eq NewlineModeDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Handle.Types
  • Ord NewlineModeDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Handle.Types
  • Read NewlineModeDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Handle.Types
  • Show NewlineModeDefined in ghc-internal-9.1003.0 · GHC.Internal.IO.Handle.Types