| Copyright | (c) The University of Glasgow 2001 |
|---|---|
| License | BSD-style (see the file libraries/base/LICENSE) |
| Maintainer | libraries@haskell.org |
| Stability | stable |
| Portability | portable |
| Safe Haskell | Trustworthy |
| Language | Haskell2010 |
System.IO
Contents
Description
The standard IO library.
A value of type is a computation which, when performed,does some I/O before returning a value of typeIO aa.
There is really only one way to "perform" an I/O action: bind it toMain.main in your program. When your program is run, the I/O willbe performed. It isn't possible to perform I/O from an arbitraryfunction, unless that function is itself in theIO monad and calledat some point, directly or indirectly, fromMain.main.
IO is a monad, soIO actions can be combined using either the do-notationor the>> and>>= operations from theMonad class.
| MonadIOSource# | Since: 2.1 |
| FunctorIOSource# | Since: 2.1 |
| MonadFixIOSource# | Since: 2.1 |
| MonadFailIOSource# | Since: 4.9.0.0 |
| ApplicativeIOSource# | Since: 2.1 |
| MonadPlusIOSource# | Since: 4.9.0.0 |
| AlternativeIOSource# | Since: 4.9.0.0 |
| MonadIOIOSource# | Since: 4.9.0.0 |
| Semigroup a =>Semigroup (IO a)Source# | Since: 4.10.0.0 |
| Monoid a =>Monoid (IO a)Source# | Since: 4.9.0.0 |
| a ~ () =>HPrintfType (IO a)Source# | Since: 4.7.0.0 |
| a ~ () =>PrintfType (IO a)Source# | Since: 4.7.0.0 |
fixIO :: (a ->IO a) ->IO aSource#
The implementation ofmfix forIO. If the function passed tofixIO inspects its argument, the resulting action will throwFixIOException.
File and directory names are values of typeString, whose precise meaning is operating system dependent. Files can be opened, yielding a handle which can then be used to operate on the contents of that file.
Haskell defines operations to read and write characters from and to files, represented by values of typeHandle. Each value of this type is ahandle: a record used by the Haskell run-time system tomanage I/O with file system objects. A handle has at least the following properties:
Most handles will also have a current I/O position indicating where the next input or output operation will occur. A handle isreadable if it manages only input or both input and output; likewise, it iswritable if it manages only output or both input and output. A handle isopen 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 theShow andEq 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.
GHC note: aHandle will be automatically closed when the garbage collector detects that it has become unreferenced by the program. However, relying on this behaviour is not generally recommended: the garbage collector is unpredictable. If possible, use an explicithClose to closeHandles when they are no longer required. GHC does not currently attempt to free up file descriptors when they have run out, it is your responsibility to ensure that this doesn't happen.
Three handles are allocated during program initialisation, and are initially open.
withFile ::FilePath ->IOMode -> (Handle ->IO r) ->IO rSource#
opens a file usingwithFile name mode actopenFile and passes the resulting handle to the computationact. The handle will be closed on exit fromwithFile, whether by normal termination or by raising an exception. If closing the handle raises an exception, then this exception will be raised bywithFile rather than any exception raised byact.
openFile ::FilePath ->IOMode ->IOHandleSource#
ComputationopenFilefile mode allocates and returns a new, open handle to manage the filefile. It manages input ifmode isReadMode, output ifmode isWriteMode orAppendMode, and both input and output if mode isReadWriteMode.
If the file does not exist and it is opened for output, it should be created as a new file. Ifmode isWriteMode and the file already exists, then it should be truncated to zero length. Some operating systems delete empty files, so there is no guarantee that the file will exist following anopenFile withmodeWriteMode unless it is subsequently written to successfully. The handle is positioned at the end of the file ifmode isAppendMode, and otherwise at the beginning (in which case its internal position is 0). The initial buffer mode is implementation-dependent.
This operation may fail with:
isAlreadyInUseError if the file is already open and cannot be reopened;isDoesNotExistError if the file does not exist; orisPermissionError if the user does not have permission to open the file.Note: if you will be working with files containing binary data, you'll want to be usingopenBinaryFile.
SeeopenFile
Constructors
| ReadMode | |
| WriteMode | |
| AppendMode | |
| ReadWriteMode |
| EnumIOModeSource# | Since: 4.2.0.0 |
| EqIOModeSource# | Since: 4.2.0.0 |
| OrdIOModeSource# | Since: 4.2.0.0 |
| ReadIOModeSource# | Since: 4.2.0.0 |
| ShowIOModeSource# | Since: 4.2.0.0 |
| IxIOModeSource# | Since: 4.2.0.0 |
Instance detailsDefined inGHC.IO.IOMode | |
hClose ::Handle ->IO ()Source#
ComputationhClosehdl makes handlehdl closed. Before the computation finishes, ifhdl is writable its buffer is flushed as forhFlush. PerforminghClose 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. IfhClose fails for any reason, any further operations (apart fromhClose) on the handle will still fail as ifhdl had been successfully closed.
These functions are also exported by thePrelude.
readFile ::FilePath ->IOStringSource#
ThereadFile function reads a file and returns the contents of the file as a string. The file is read lazily, on demand, as withgetContents.
writeFile ::FilePath ->String ->IO ()Source#
The computationwriteFilefile str function writes the stringstr, to the filefile.
appendFile ::FilePath ->String ->IO ()Source#
The computationappendFilefile str function appends the stringstr, to the filefile.
Note thatwriteFile andappendFile write a literal string to a file. To write a value of any printable type, as withprint, use theshow function to convert the value to a string first.
main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
Implementations should enforce as far as possible, at least locally to the Haskell process, multiple-reader single-writer locking on files. That is,there may either be many handles on the same file which manage input, or just one handle on the file which manages output. If any open or semi-closed handle is managing a file for output, no new handle can be allocated for that file. If any open or semi-closed handle is managing a file for input, new handles can only be allocated if they do not manage output. Whether two files are the same is implementation-dependent, but they should normally be the same if they have the same absolute path name and neither has been renamed, for example.
Warning: thereadFile operation holds a semi-closed handle on the file until the entire contents of the file have been consumed. It follows that an attempt to write to a file (usingwriteFile, for example) that was earlier opened byreadFile will usually result in failure withisAlreadyInUseError.
hFileSize ::Handle ->IOIntegerSource#
For a handlehdl which attached to a physical file,hFileSizehdl returns the size of that file in 8-bit bytes.
hSetFileSize ::Handle ->Integer ->IO ()Source#
hSetFileSizehdlsize truncates the physical file with handlehdl tosize bytes.
hIsEOF ::Handle ->IOBoolSource#
For a readable handlehdl,hIsEOFhdl returnsTrue if no further input can be taken fromhdl or for a physical file, if the current I/O position is equal to the length of the file. Otherwise, it returnsFalse.
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.
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, orflushed, from the internal buffer according to the buffer mode:
hFlush is issued, or the handle is closed.hFlush is issued, or the handle is closed.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:
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 (MaybeInt) | block-buffering should be enabled if possible. The size of the buffer is |
| EqBufferModeSource# | Since: 4.2.0.0 |
Instance detailsDefined inGHC.IO.Handle.Types | |
| OrdBufferModeSource# | Since: 4.2.0.0 |
Instance detailsDefined inGHC.IO.Handle.Types Methods compare ::BufferMode ->BufferMode ->Ordering# (<) ::BufferMode ->BufferMode ->Bool# (<=) ::BufferMode ->BufferMode ->Bool# (>) ::BufferMode ->BufferMode ->Bool# (>=) ::BufferMode ->BufferMode ->Bool# max ::BufferMode ->BufferMode ->BufferMode# min ::BufferMode ->BufferMode ->BufferMode# | |
| ReadBufferModeSource# | Since: 4.2.0.0 |
Instance detailsDefined inGHC.IO.Handle.Types | |
| ShowBufferModeSource# | Since: 4.2.0.0 |
Instance detailsDefined inGHC.IO.Handle.Types | |
hSetBuffering ::Handle ->BufferMode ->IO ()Source#
ComputationhSetBufferinghdl mode sets the mode of buffering for handlehdl on subsequent reads and writes.
If the buffer mode is changed fromBlockBuffering orLineBuffering toNoBuffering, then
hdl is writable, the buffer is flushed as forhFlush;hdl is not writable, the contents of the buffer is 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.hGetBuffering ::Handle ->IOBufferModeSource#
ComputationhGetBufferinghdl returns the current buffering mode forhdl.
hFlush ::Handle ->IO ()Source#
The actionhFlushhdl causes any items buffered for output in handlehdl 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.hGetPosn ::Handle ->IOHandlePosnSource#
ComputationhGetPosnhdl returns the current I/O position ofhdl as a value of the abstract typeHandlePosn.
hSetPosn ::HandlePosn ->IO ()Source#
| EqHandlePosnSource# | Since: 4.1.0.0 |
Instance detailsDefined inGHC.IO.Handle | |
| ShowHandlePosnSource# | Since: 4.1.0.0 |
Instance detailsDefined inGHC.IO.Handle | |
hSeek ::Handle ->SeekMode ->Integer ->IO ()Source#
ComputationhSeekhdl mode i sets the position of handlehdl depending onmode. The offseti is given in terms of 8-bit bytes.
Ifhdl 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 (seehIsSeekable), 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:
isIllegalOperationError if the Handle is not seekable, or does not support the requested seek mode.isPermissionError if a system resource limit would be exceeded.A mode that determines the effect ofhSeekhdl mode i.
Constructors
| AbsoluteSeek | the position of |
| RelativeSeek | the position of |
| SeekFromEnd | the position of |
| EnumSeekModeSource# | Since: 4.2.0.0 |
Instance detailsDefined inGHC.IO.Device Methods succ ::SeekMode ->SeekModeSource# pred ::SeekMode ->SeekModeSource# toEnum ::Int ->SeekModeSource# fromEnum ::SeekMode ->IntSource# enumFrom ::SeekMode -> [SeekMode]Source# enumFromThen ::SeekMode ->SeekMode -> [SeekMode]Source# enumFromTo ::SeekMode ->SeekMode -> [SeekMode]Source# enumFromThenTo ::SeekMode ->SeekMode ->SeekMode -> [SeekMode]Source# | |
| EqSeekModeSource# | Since: 4.2.0.0 |
| OrdSeekModeSource# | Since: 4.2.0.0 |
| ReadSeekModeSource# | Since: 4.2.0.0 |
| ShowSeekModeSource# | Since: 4.2.0.0 |
| IxSeekModeSource# | Since: 4.2.0.0 |
Instance detailsDefined inGHC.IO.Device Methods range :: (SeekMode,SeekMode) -> [SeekMode]Source# index :: (SeekMode,SeekMode) ->SeekMode ->IntSource# unsafeIndex :: (SeekMode,SeekMode) ->SeekMode ->Int inRange :: (SeekMode,SeekMode) ->SeekMode ->BoolSource# rangeSize :: (SeekMode,SeekMode) ->IntSource# unsafeRangeSize :: (SeekMode,SeekMode) ->Int | |
hTell ::Handle ->IOIntegerSource#
ComputationhTellhdl returns the current position of the handlehdl, as the number of bytes from the beginning of the file. The value returned may be subsequently passed tohSeek to reposition the handle to the current position.
This operation may fail with:
isIllegalOperationError if the Handle is not seekable.hWaitForInput ::Handle ->Int ->IOBoolSource#
ComputationhWaitForInputhdl t waits until input is available on handlehdl. It returnsTrue as soon as input is available onhdl, orFalse if no input is available withint milliseconds. Note thathWaitForInput waits until one or more fullcharacters are available, which means that it needs to do decoding, and hence may fail with a decoding error.
Ift is less than zero, thenhWaitForInput waits indefinitely.
This operation may fail with:
isEOFError if the end of file has been reached.NOTE for GHC users: unless you use the-threaded flag,hWaitForInput hdl t wheret >= 0 will block all other Haskell threads for the duration of the call. It behaves like asafe foreign call in this respect.
hReady ::Handle ->IOBoolSource#
ComputationhReadyhdl indicates whether at least one item is available for input from handlehdl.
This operation may fail with:
isEOFError if the end of file has been reached.hGetChar ::Handle ->IOCharSource#
ComputationhGetCharhdl reads a character from the file or channel managed byhdl, blocking until a character is available.
This operation may fail with:
isEOFError if the end of file has been reached.hGetLine ::Handle ->IOStringSource#
ComputationhGetLinehdl reads a line from the file or channel managed byhdl.
This operation may fail with:
isEOFError if the end of file is encountered when reading thefirst character of the line.IfhGetLine encounters end-of-file at any other point while reading in a line, it is treated as a line terminator and the (partial) line is returned.
hLookAhead ::Handle ->IOCharSource#
ComputationhLookAhead 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:
isEOFError if the end of file has been reached.hGetContents ::Handle ->IOStringSource#
ComputationhGetContentshdl returns the list of characters corresponding to the unread portion of the channel or file managed byhdl, which is put into an intermediate state,semi-closed. In this state,hdl is effectively closed, but items are read fromhdl on demand and accumulated in a special list returned byhGetContentshdl.
Any operation that fails because a handle is closed, also fails if a handle is semi-closed. The only exception ishClose. A semi-closed handle becomes closed:
hClose is applied to it;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:
isEOFError if the end of file has been reached.hPutChar ::Handle ->Char ->IO ()Source#
ComputationhPutCharhdl ch writes the characterch to the file or channel managed byhdl. Characters may be buffered if buffering is enabled forhdl.
This operation may fail with:
isFullError if the device is full; orisPermissionError if another system resource limit would be exceeded.hPutStr ::Handle ->String ->IO ()Source#
ComputationhPutStrhdl s writes the strings to the file or channel managed byhdl.
This operation may fail with:
isFullError if the device is full; orisPermissionError if another system resource limit would be exceeded.hPrint ::Show a =>Handle -> a ->IO ()Source#
ComputationhPrinthdl t writes the string representation oft given by theshows function to the file or channel managed byhdl and appends a newline.
This operation may fail with:
isFullError if the device is full; orisPermissionError if another system resource limit would be exceeded.These functions are also exported by thePrelude.
interact :: (String ->String) ->IO ()Source#
Theinteract function takes a function of typeString->String as its argument. The entire input from the standard input device is passed to this function as its argument, and the resulting string is output on the standard output device.
print ::Show a => a ->IO ()Source#
Theprint function outputs a value of any printable type to the standard output device. Printable types are those that are instances of classShow;print converts values to strings for output using theshow operation and adds a newline.
For example, a program to print the first 20 integers and their powers of 2 could be written as:
main = print ([(n, 2^n) | n <- [0..19]])
ThegetContents operation returns all user input as a single string, which is read lazily as it is needed (same ashGetContentsstdin).
withBinaryFile ::FilePath ->IOMode -> (Handle ->IO r) ->IO rSource#
opens a file usingwithBinaryFile name mode actopenBinaryFile and passes the resulting handle to the computationact. The handle will be closed on exit fromwithBinaryFile, whether by normal termination or by raising an exception.
openBinaryFile ::FilePath ->IOMode ->IOHandleSource#
LikeopenFile, but open the file in binary mode. On Windows, reading a file in text mode (which is the default) will translate CRLF to LF, and writing will translate LF to CRLF. This is usually what you want with text files. With binary files this is undesirable; also, as usual under Microsoft operating systems, text mode treats control-Z as EOF. Binary mode turns off all special treatment of end-of-line and end-of-file characters. (See alsohSetBinaryMode.)
hSetBinaryMode ::Handle ->Bool ->IO ()Source#
Select binary mode (True) or text mode (False) on a open handle. (See alsoopenBinaryFile.)
This has the same effect as callinghSetEncoding withchar8, together withhSetNewlineMode withnoNewlineTranslation.
hPutBuf ::Handle ->Ptr a ->Int ->IO ()Source#
hPutBufhdl buf count writescount 8-bit bytes from the bufferbuf to the handlehdl. It returns ().
hPutBuf ignores any text encoding that applies to theHandle, writing the bytes directly to the underlying file or device.
hPutBuf ignores the prevailingTextEncoding andNewlineMode on theHandle, 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).hGetBuf ::Handle ->Ptr a ->Int ->IOIntSource#
hGetBufhdl buf count reads data from the handlehdl into the bufferbuf until either EOF is reached orcount 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 ifcount is zero).
hGetBuf never raises an EOF exception, instead it returns a value smaller thancount.
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 prevailingTextEncoding andNewlineMode on theHandle, and reads bytes directly.
hGetBufSome ::Handle ->Ptr a ->Int ->IOIntSource#
hGetBufSomehdl buf count reads data from the handlehdl into the bufferbuf. If there is any data available to read, thenhGetBufSome returns it immediately; it only blocks if there is no data to be read.
It returns the number of bytes actually read. This may be zero if EOF was reached before any data was read (or ifcount is zero).
hGetBufSome never raises an EOF exception, instead it returns a value smaller thancount.
If the handle is a pipe or socket, and the writing end is closed,hGetBufSome will behave as if EOF was reached.
hGetBufSome ignores the prevailingTextEncoding andNewlineMode on theHandle, and reads bytes directly.
hGetBufNonBlocking ::Handle ->Ptr a ->Int ->IOIntSource#
hGetBufNonBlockinghdl buf count reads data from the handlehdl into the bufferbuf until either EOF is reached, orcount 8-bit bytes have been read, or there is no more data available to read immediately.
hGetBufNonBlocking is identical tohGetBuf, 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 callinghGetBufNonBlocking, usehWaitForInput.
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 prevailingTextEncoding andNewlineMode on theHandle, and reads bytes directly.
NOTE: on Windows, this function does not work correctly; it behaves identically tohGetBuf.
Arguments
| ::FilePath | Directory in which to create the file |
| ->String | File name template. If the template is "foo.ext" then the created file will be "fooXXX.ext" where XXX is some random number. Note that this should not contain any path separator characters. |
| ->IO (FilePath,Handle) |
The function creates a temporary file in ReadWrite mode. The created file isn't deleted automatically, so you need to delete it manually.
The file is created with permissions such that only the current user can read/write it.
With some exceptions (see below), the file will be created securely in the sense that an attacker should not be able to cause openTempFile to overwrite another file on the filesystem using your credentials, by putting symbolic links (on Unix) in the place where the temporary file is to be created. On Unix theO_CREAT andO_EXCL flags are used to prevent this attack, but note thatO_EXCL is sometimes not supported on NFS filesystems, so if you rely on this behaviour it is best to use local filesystems only.
openBinaryTempFile ::FilePath ->String ->IO (FilePath,Handle)Source#
LikeopenTempFile, but opens the file in binary mode. SeeopenBinaryFile for more comments.
openTempFileWithDefaultPermissions ::FilePath ->String ->IO (FilePath,Handle)Source#
LikeopenTempFile, but uses the default file permissions
openBinaryTempFileWithDefaultPermissions ::FilePath ->String ->IO (FilePath,Handle)Source#
LikeopenBinaryTempFile, but uses the default file permissions
A text-modeHandle has an associatedTextEncoding, which is used to decode bytes into Unicode characters when reading, and encode Unicode characters into bytes when writing.
The defaultTextEncoding is the same as the default encoding on your system, which is also available aslocaleEncoding. (GHC note: on Windows, we currently do not support double-byte encodings; if the console's code page is unsupported, thenlocaleEncoding will belatin1.)
Encoding and decoding errors are always detected and reported, except during lazy I/O (hGetContents,getContents, andreadFile), where a decoding error merely results in termination of the character stream, as with other I/O errors.
hSetEncoding ::Handle ->TextEncoding ->IO ()Source#
The actionhSetEncodinghdlencoding changes the text encoding for the handlehdl toencoding. The default encoding when aHandle is created islocaleEncoding, namely the default encoding for the current locale.
To create aHandle with no encoding at all, useopenBinaryFile. To stop further encoding or decoding on an existingHandle, usehSetBinaryMode.
hSetEncoding may need to flush buffered data in order to change the encoding.
hGetEncoding ::Handle ->IO (MaybeTextEncoding)Source#
Return the currentTextEncoding for the specifiedHandle, orNothing if theHandle is in binary mode.
Note that theTextEncoding remembers nothing about the state of the encoder/decoder in use on thisHandle. For example, if the encoding in use is UTF-16, then usinghGetEncoding andhSetEncoding to save and restore the encoding may result in an extra byte-order-mark being written to the file.
ATextEncoding is a specification of a conversion scheme between sequences of bytes and sequences of Unicode characters.
For example, UTF-8 is an encoding of Unicode characters into a sequence of bytes. TheTextEncoding for UTF-8 isutf8.
| ShowTextEncodingSource# | Since: 4.3.0.0 |
Instance detailsDefined inGHC.IO.Encoding.Types | |
The Latin1 (ISO8859-1) encoding. This encoding maps bytes directly to the first 256 Unicode code points, and is thus not a complete Unicode encoding. An attempt to write a character greater than '\255' to aHandle using thelatin1 encoding will result in an error.
The UTF-8 Unicode encoding
utf8_bom ::TextEncodingSource#
The UTF-8 Unicode encoding, with a byte-order-mark (BOM; the byte sequence 0xEF 0xBB 0xBF). This encoding behaves likeutf8, except that on input, the BOM sequence is ignored at the beginning of the stream, and on output, the BOM sequence is prepended.
The byte-order-mark is strictly unnecessary in UTF-8, but is sometimes used to identify the encoding of a file.
The UTF-16 Unicode encoding (a byte-order-mark should be used to indicate endianness).
The UTF-16 Unicode encoding (litte-endian)
The UTF-16 Unicode encoding (big-endian)
The UTF-32 Unicode encoding (a byte-order-mark should be used to indicate endianness).
The UTF-32 Unicode encoding (litte-endian)
The UTF-32 Unicode encoding (big-endian)
localeEncoding ::TextEncodingSource#
The Unicode encoding of the current locale
This is the initial locale encoding: if it has been subsequently changed bysetLocaleEncoding this value will not reflect that change.
An encoding in which Unicode code points are translated to bytes by taking the code point modulo 256. When decoding, bytes are translated directly into the equivalent code point.
This encoding never fails in either direction. However, encoding discards information, so encode followed by decode is not the identity.
Since: 4.4.0.0
mkTextEncoding ::String ->IOTextEncodingSource#
Look up the named Unicode encoding. May fail with
isDoesNotExistError if the encoding is unknownThe set of known encodings is system-dependent, but includes at least:
UTF-8
UTF-16,UTF-16BE,UTF-16LEUTF-32,UTF-32BE,UTF-32LEThere is additional notation (borrowed from GNU iconv) for specifying how illegal characters are handled:
//IGNORE, e.g.UTF-8//IGNORE, will cause all illegal sequences on input to be ignored, and on output will drop all code points that have no representation in the target encoding.//TRANSLIT will choose a replacement character for illegal sequences or code points.//ROUNDTRIP will use a PEP383-style escape mechanism to represent any invalid bytes in the input as Unicode codepoints (specifically, as lone surrogates, which are normally invalid in UTF-32). Upon output, these special codepoints are detected and turned back into the corresponding original byte.In theory, this mechanism allows arbitrary data to be roundtripped via aString with no loss of data. In practice, there are two limitations to be aware of:
On Windows, you can access supported code pages with the prefixCP; for example,"CP1250".
In Haskell, a newline is always represented by the character '\n'. However, in files and external character streams, a newline may be represented by another character sequence, such as '\r\n'.
A text-modeHandle has an associatedNewlineMode that specifies how to transate newline characters. TheNewlineMode specifies the input and output translation separately, so that for instance you can translate '\r\n' to '\n' on input, but leave newlines as '\n' on output.
The defaultNewlineMode for aHandle isnativeNewlineMode, which does no translation on Unix systems, but translates '\r\n' to '\n' and back on Windows.
Binary-modeHandles do no newline translation at all.
hSetNewlineMode ::Handle ->NewlineMode ->IO ()Source#
Set theNewlineMode on the specifiedHandle. All buffered data is flushed first.
The representation of a newline in the external file or stream.
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
| NewlineMode | |
| EqNewlineModeSource# | Since: 4.2.0.0 |
Instance detailsDefined inGHC.IO.Handle.Types | |
| OrdNewlineModeSource# | Since: 4.3.0.0 |
Instance detailsDefined inGHC.IO.Handle.Types Methods compare ::NewlineMode ->NewlineMode ->Ordering# (<) ::NewlineMode ->NewlineMode ->Bool# (<=) ::NewlineMode ->NewlineMode ->Bool# (>) ::NewlineMode ->NewlineMode ->Bool# (>=) ::NewlineMode ->NewlineMode ->Bool# | |
| ReadNewlineModeSource# | Since: 4.3.0.0 |
Instance detailsDefined inGHC.IO.Handle.Types | |
| ShowNewlineModeSource# | Since: 4.3.0.0 |
Instance detailsDefined inGHC.IO.Handle.Types | |
noNewlineTranslation ::NewlineModeSource#
Do no newline translation at all.
noNewlineTranslation = NewlineMode { inputNL = LF, outputNL = LF }universalNewlineMode ::NewlineModeSource#
Map '\r\n' into '\n' on input, and '\n' to the native newline represetnation on output. This mode can be used on any platform, and works with text files using any newline convention. The downside is thatreadFile >>= writeFile might yield a different file.
universalNewlineMode = NewlineMode { inputNL = CRLF, outputNL = nativeNewline }nativeNewlineMode ::NewlineModeSource#
Use the native newline representation on both input and output
nativeNewlineMode = NewlineMode { inputNL = nativeNewline outputNL = nativeNewline }Produced byHaddock version 2.20.0