1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
|
<title>The Haskell 98 Library Report: IO</title>
<body bgcolor="#ffffff"> <i>The Haskell 98 Library Report</i><br> <a href="index.html">top</a> | <a href="monad.html">back</a> | <a href="directory.html">next</a> | <a href="libindex.html">contents</a> <br><hr>
<a name="IO"></a><a name="sect11"></a>
<h2>11<tt> </tt>Input/Output</h2>
<p>
<table border=2 cellpadding=3>
<tr><td>
<tt><br>
module IO (<br>
Handle, HandlePosn,<br>
IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),<br>
BufferMode(NoBuffering,LineBuffering,BlockBuffering),<br>
SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),<br>
stdin, stdout, stderr, <br>
openFile, hClose, hFileSize, hIsEOF, isEOF,<br>
hSetBuffering, hGetBuffering, hFlush, <br>
hGetPosn, hSetPosn, hSeek, <br>
hWaitForInput, hReady, hGetChar, hGetLine, hLookAhead, hGetContents, <br>
hPutChar, hPutStr, hPutStrLn, hPrint,<br>
hIsOpen, hIsClosed, hIsReadable, hIsWritable, hIsSeekable,<br>
isAlreadyExistsError, isDoesNotExistError, isAlreadyInUseError, <br>
isFullError, isEOFError,<br>
isIllegalOperation, isPermissionError, isUserError, <br>
ioeGetErrorString, ioeGetHandle, ioeGetFileName,<br>
try, bracket, bracket_<br>
<br>
-- ...and what the Prelude exports<br>
IO, FilePath, IOError, ioError, userError, catch, interact,<br>
putChar, putStr, putStrLn, print, getChar, getLine, getContents,<br>
readFile, writeFile, appendFile, readIO, readLn<br>
) where<br>
<br>
import Ix(Ix)<br>
<br>
data Handle = ... -- implementation-dependent<br>
instance Eq Handle where ...<br>
instance Show Handle where .. -- implementation-dependent<br>
<br>
data HandlePosn = ... -- implementation-dependent<br>
instance Eq HandlePosn where ...<br>
instance Show HandlePosn where --- -- implementation-dependent<br>
<br>
<br>
data IOMode = ReadMode | WriteMode | AppendMode | ReadWriteMode<br>
deriving (Eq, Ord, Ix, Bounded, Enum, Read, Show)<br>
data BufferMode = NoBuffering | LineBuffering <br>
| BlockBuffering (Maybe Int)<br>
deriving (Eq, Ord, Read, Show)<br>
data SeekMode = AbsoluteSeek | RelativeSeek | SeekFromEnd<br>
deriving (Eq, Ord, Ix, Bounded, Enum, Read, Show)<br>
<br>
stdin, stdout, stderr :: Handle<br>
<br>
openFile :: FilePath -> IOMode -> IO Handle<br>
hClose :: Handle -> IO ()<br>
</tt></td></tr></table>
<table border=2 cellpadding=3>
<tr><td>
<tt><br>
hFileSize :: Handle -> IO Integer<br>
hIsEOF :: Handle -> IO Bool<br>
isEOF :: IO Bool<br>
isEOF = hIsEOF stdin<br>
<br>
hSetBuffering :: Handle -> BufferMode -> IO ()<br>
hGetBuffering :: Handle -> IO BufferMode<br>
hFlush :: Handle -> IO () <br>
hGetPosn :: Handle -> IO HandlePosn<br>
hSetPosn :: HandlePosn -> IO () <br>
hSeek :: Handle -> SeekMode -> Integer -> IO () <br>
<br>
hWaitForInput :: Handle -> Int -> IO Bool<br>
hReady :: Handle -> IO Bool <br>
hReady h = hWaitForInput h 0<br>
hGetChar :: Handle -> IO Char<br>
hGetLine :: Handle -> IO String<br>
hLookAhead :: Handle -> IO Char<br>
hGetContents :: Handle -> IO String<br>
hPutChar :: Handle -> Char -> IO ()<br>
hPutStr :: Handle -> String -> IO ()<br>
hPutStrLn :: Handle -> String -> IO ()<br>
hPrint :: Show a => Handle -> a -> IO ()<br>
<br>
hIsOpen :: Handle -> IO Bool<br>
hIsClosed :: Handle -> IO Bool<br>
hIsReadable :: Handle -> IO Bool<br>
hIsWritable :: Handle -> IO Bool<br>
hIsSeekable :: Handle -> IO Bool<br>
<br>
isAlreadyExistsError :: IOError -> Bool<br>
isDoesNotExistError :: IOError -> Bool<br>
isAlreadyInUseError :: IOError -> Bool<br>
isFullError :: IOError -> Bool<br>
isEOFError :: IOError -> Bool<br>
isIllegalOperation :: IOError -> Bool<br>
isPermissionError :: IOError -> Bool<br>
isUserError :: IOError -> Bool<br>
<br>
ioeGetErrorString :: IOError -> String<br>
ioeGetHandle :: IOError -> Maybe Handle<br>
ioeGetFileName :: IOError -> Maybe FilePath<br>
<br>
try :: IO a -> Either IOError a<br>
bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c<br>
bracket_ :: IO a -> (a -> IO b) -> IO c -> IO c<br>
</tt></td></tr></table>
<p>
The monadic I/O system used in Haskell is described by the
Haskell language report. Commonly used I/O functions such as
<tt>print</tt> are part of the standard prelude and need not be explicitly
imported. This library contain more advanced I/O features.
Some related operations on file systems are contained in the
<tt>Directory</tt> library.<a name="IOError"></a><p>
<a name="sect11.1"></a>
<h3>11.1<tt> </tt>I/O Errors</h3>
Errors of type <tt>IOError</tt> are used by the I/O monad. This is an
abstract type; the library provides functions to interrogate and
construct values in <tt>IOError</tt>:
<UL><LI>
<tt>isAlreadyExistsError
</tt> -- the operation failed because one of its
arguments already exists.
<LI>
<tt>isDoesNotExistError
</tt> -- the operation failed because one of its
arguments does not exist.
<LI>
<tt>isAlreadyInUseError
</tt> -- the operation failed because one of its
arguments is a single-use resource, which is already being used (for
example, opening the same file twice for writing might give this
error).
<LI>
<tt>isFullError
</tt> -- the operation failed because the device is full.
<LI>
<tt>isEOFError
</tt> -- the operation failed because the end of file
has been reached.
<LI>
<tt>isIllegalOperation
</tt> -- the operation is not possible.
<LI>
<tt>isPermissionError
</tt> -- the operation failed because the user does not
have sufficient operating system privilege to perform that operation.
<LI>
<tt>isUserError
</tt> -- a programmer-defined error value has been raised using
<tt>fail</tt>.
</UL>
All these functions return return a <tt>Bool</tt>, which is <tt>True</tt> if
its argument is the corresponding kind of error, and <tt>False
</tt>otherwise. <p>
Any computation which returns an <tt>IO</tt> result may fail with
<tt>isIllegalOperationError</tt>. Additional errors which could be raised by
an implementation are listed after the corresponding operation. In
some cases, an implementation will not be able to distinguish between
the possible error causes. In this case it should return
<tt>isIllegalOperationError</tt>.<p>
Three additional functions are provided to obtain information about an
error value. These are <tt>ioeGetHandle</tt> which
returns <tt>Just</tt> <I>hdl</I> if the error value refers to handle <I>hdl</I> and
<tt>Nothing</tt> otherwise; <tt>ioeGetFileName</tt> which
returns <tt>Just</tt> <I>name</I> if the error value refers to file <I>name</I>, and
<tt>Nothing</tt> otherwise; and <tt>ioeGetErrorString</tt> which returns a
string. For "user" errors (those which are raised using <tt>fail</tt>),
the string returned by <tt>ioeGetErrorString</tt> is the argument that was passed to
<tt>fail</tt>; for all other errors, the string is implementation-dependent.<p>
The <tt>try</tt> function returns an error in a computation explicitly using
the <tt>Either</tt> type.<p>
The <tt>bracket</tt> function
captures a common allocate, compute, deallocate idiom in which the
deallocation step must occur even in the case of an error during
computation. This is similar to try-catch-finally in Java.<p>
<tt>module IO where<br>
<br>
-- Just provide an implementation of the system-indendent<br>
-- actions that IO exports.<br>
<br>
try :: IO a -> IO (Either IOError a)<br>
try f = catch (do r <- f<br>
return (Right r))<br>
(return . Left)<br>
<br>
bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c<br>
bracket before after m = do<br>
x <- before<br>
rs <- try (m x)<br>
after x<br>
case rs of<br>
Right r -> return r<br>
Left e -> ioError e<br>
<br>
-- variant of the above where middle computation doesn't want x<br>
bracket_ :: IO a -> (a -> IO b) -> IO c -> IO c<br>
bracket_ before after m = do<br>
x <- before<br>
rs <- try m<br>
after x<br>
case rs of<br>
Right r -> return r<br>
Left e -> ioError e<br>
<p>
</tt><a name="sect11.2"></a>
<h3>11.2<tt> </tt>Files and Handles</h3>
Haskell interfaces to the external world through an abstract <I>file
system</I>. This file system is a collection of named <I>file
system objects</I>, which may be organised
in <I>directories</I> (see <tt>Directory</tt>).
In some implementations, directories may themselves be file system
objects and could be entries in other directories. For simplicity,
any non-directory file system object is termed a <I>file</I>,
although it could in fact be a communication channel, or any other
object recognised by the operating system. <I>Physical
files</I> are
persistent, ordered files, and normally reside on disk.<p>
File and directory names are values of type <tt>String</tt>, 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.<a name="Handles"></a><p>
<p>
Haskell defines operations to read and write characters from and to files,
represented by values of type <tt>Handle</tt>. Each value of this type is a
<I>handle</I>: a record used by the Haskell run-time system to <I>manage</I> I/O
with file system objects. A handle has at least the following properties:<p>
<UL><LI>
whether it manages input or output or both;
<LI>
whether it is <I>open</I>, <I>closed</I> or <I>semi-closed</I>;
<LI>
whether the object is seekable;
<LI>
whether buffering is disabled, or enabled on a line or block basis;
<LI>
a buffer (whose length may be zero).
</UL><p>
Most handles will also have a current I/O position indicating where the next
input or output operation will occur. A handle is <I>readable</I> if it
manages only input or both input and output; likewise, it is <I>writable</I> if
it manages only output or both input and output. A handle is <I>open</I> 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 <tt>Show</tt> and <tt>Eq</tt> 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 <tt>==</tt> only to itself; no attempt
is made to compare the internal state of different handles for equality.<a name="SemiClosed"></a><p>
<a name="sect11.2.1"></a>
<h4>11.2.1<tt> </tt>Semi-Closed Handles</h4>
<p>
The operation <tt>hGetContents</tt> puts a handle <I>hdl</I> into an intermediate
state, <I>semi-closed</I>. In this state, <I>hdl</I> is effectively closed,
but items are read from <I>hdl</I> on demand and accumulated in a special
stream returned by <tt>hGetContents</tt> <I>hdl</I>.
Any operation except for <tt>hClose</tt> that fails because a handle is
closed, also fails if a handle is semi-closed. A semi-closed handle
becomes closed:
<UL><LI>
if <tt>hClose</tt> is applied to it;
<LI>
if an I/O error occurs when reading an item from the
file item from the stream;
<LI>
or once the entire contents of the file has been read.
</UL><p>
Once a semi-closed handle becomes closed, the contents of the
associated stream becomes fixed, and is the list of those items which
were successfully read from that handle. Any I/O errors encountered while
a handle is semi-closed are simply discarded.
<a name="StandardHandles"></a><p>
<a name="sect11.2.2"></a>
<h4>11.2.2<tt> </tt>Standard Handles</h4>
<p>
Three handles are allocated during program initialisation. The first
two (<tt>stdin</tt> and <tt>stdout</tt>) manage input or output from the Haskell
program's standard input or output channel respectively. The third
(<tt>stderr</tt>) manages output to the standard error channel. These
handles are initially open.<a name="OpeningClosing"></a><p>
<a name="sect11.3"></a>
<h3>11.3<tt> </tt>Opening and Closing Files</h3>
<a name="Opening"></a><p>
<a name="sect11.3.1"></a>
<h4>11.3.1<tt> </tt>Opening Files</h4>
<p>
Computation <tt>openFile</tt> <I>file</I> <I>mode</I> allocates and
returns a new, open handle to manage the file <I>file</I>.
It manages
input if <I>mode</I> is <tt>ReadMode</tt>,
output if <I>mode</I> is <tt>WriteMode</tt> or
<tt>AppendMode</tt>, and both input and output if mode is
<tt>ReadWriteMode</tt>.<p>
If the file does not exist and it is opened for output, it should be created
as a new file. If <I>mode</I> is <tt>WriteMode</tt> 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 an
<tt>openFile</tt> with <I>mode</I> <tt>WriteMode</tt> unless it is subsequently written to
successfully. The handle is positioned at the end of the file if <I>mode</I> is
<tt>AppendMode</tt>, and otherwise at the beginning (in which case its internal I/O
position is 0). The initial buffer mode is implementation-dependent.<p>
If <tt>openFile</tt> fails on a file opened for output, the file may still
have been created if it did not already exist.<p>
Implementations should enforce as far as possible, locally to the
Haskell process, multiple-reader single-writer locking on files.
Thus 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.<p>
<I>Error reporting</I>: the <tt>openFile</tt> computation may fail with
<tt>isAlreadyInUseError</tt> if the file is already open and cannot be
reopened;
<tt>isDoesNotExistError</tt> if the file does not exist; or
<tt>isPermissionError</tt> if the user does not have
permission to open the file.<a name="Closing"></a><p>
<a name="sect11.3.2"></a>
<h4>11.3.2<tt> </tt>Closing Files</h4>
<p>
Computation <tt>hClose</tt> <I>hdl</I> makes handle <I>hdl</I> closed. Before the
computation finishes, if <I>hdl</I> is writable its buffer is flushed as
for <tt>hFlush</tt>.
If the operation fails for any reason, any further operations on the
handle will still fail as if <I>hdl</I> had been successfully closed.<a name="FileSize"></a><p>
<a name="sect11.4"></a>
<h3>11.4<tt> </tt>Determining the Size of a File</h3>
<p>
For a handle <I>hdl</I> which is attached to a physical file, <tt>hFileSize
</tt><I>hdl</I> returns the size of that file in 8-bit bytes (<I>>=</I> 0).<a name="EOF"></a><p>
<a name="sect11.4.1"></a>
<h4>11.4.1<tt> </tt>Detecting the End of Input</h4>
<p>
For a readable handle <I>hdl</I>, computation <tt>hIsEOF</tt> <I>hdl</I> returns <tt>True
</tt>if no further input can be taken from <I>hdl</I>; for a handle attached to a
physical file this means that the current I/O position is equal to the length of the file.
Otherwise, it returns <tt>False</tt>. The computation <tt>isEOF</tt> is identical,
except that it works only on <tt>stdin</tt>.<a name="Buffering"></a><p>
<a name="sect11.4.2"></a>
<h4>11.4.2<tt> </tt>Buffering Operations</h4>
<p>
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 from the internal buffer
according to the buffer mode:
<UL><LI>
<B>line-buffering:
</B>the entire buffer is written out whenever a newline is output, the
buffer overflows, a flush is issued, or the handle is closed.
<LI>
<B>block-buffering:
</B>the entire buffer is written out whenever it overflows, a flush is
issued, or the handle is closed.
<LI>
<B>no-buffering:
</B>output is written immediately, and never stored in the buffer.
</UL>
The buffer is emptied as soon as it has been written out.<p>
Similarly, input occurs according to the buffer mode for handle <I>hdl</I>.
<UL><LI>
<B>line-buffering:
</B>when the buffer for <I>hdl</I> is not empty, the next item is obtained from
the buffer; otherwise, when the buffer is empty, characters are read into
the buffer until the next newline character is encountered or the buffer is full. No
characters are available until the newline character is available or the buffer is full.
<LI>
<B>block-buffering:</B>
when the buffer for <I>hdl</I> becomes empty, the
next block of data is read into the buffer.
<LI>
<B>no-buffering:</B>
the next input item is read and returned.
</UL><p>
For most implementations, physical files will normally be block-buffered
and terminals will normally be line-buffered.<p>
Computation <tt>hSetBuffering</tt> <I>hdl</I> <I>mode</I> sets the
mode of buffering for handle <I>hdl</I> on subsequent reads and writes.
<UL><LI>
If <I>mode</I> is <tt>LineBuffering</tt>, line-buffering is
enabled if possible.
<LI>
If <I>mode</I> is <tt>BlockBuffering</tt> <I>size</I>, then block-buffering
is enabled if possible. The size of the buffer is <I>n</I> items
if <I>size</I> is <tt>Just </tt><I>n</I> and is otherwise implementation-dependent.
<LI>
If <I>mode</I> is <tt>NoBuffering</tt>, then buffering is disabled if possible.
</UL><p>
If the buffer mode is changed from <tt>BlockBuffering</tt> or
<tt>LineBuffering</tt> to <tt>NoBuffering</tt>, then
<UL><LI>
if <I>hdl</I> is writable, the buffer is flushed as for
<tt>hFlush</tt>;
<LI>
if <I>hdl</I> is not writable, the contents of the buffer is discarded.
</UL><p>
<I>Error reporting</I>: the <tt>hSetBuffering</tt> computation may fail with
<tt>isPermissionError</tt> if
the handle has already been used for reading or writing
and the implementation does not allow the buffering mode to
be changed.<p>
Computation <tt>hGetBuffering</tt> <I>hdl</I> returns the current buffering mode
for <I>hdl</I>.<p>
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.<a name="Flushing"></a><p>
<a name="sect11.4.3"></a>
<h4>11.4.3<tt> </tt>Flushing Buffers</h4>
<p>
Computation <tt>hFlush</tt> <I>hdl</I> causes any items buffered for output in
handle <I>hdl</I> to be sent immediately to the operating system.<p>
<I>Error reporting</I>: the <tt>hFlush</tt> computation may fail with:
<tt>isFullError</tt> if the device is full; <tt>isPermissionError</tt> if a
system resource limit would be exceeded. It is unspecified whether the
characters in the buffer are discarded or retained under these circumstances.<a name="Seeking"></a><p>
<a name="sect11.5"></a>
<h3>11.5<tt> </tt>Repositioning Handles</h3>
<p>
<a name="sect11.5.1"></a>
<h4>11.5.1<tt> </tt>Revisiting an I/O Position</h4><p>
Computation <tt>hGetPosn</tt> <I>hdl</I> returns the current I/O position of <I>hdl</I> as a
value of the abstract type <tt>HandlePosn</tt>. If a call to <tt>hGetPosn</tt><I> h</I> returns a position <I>p</I>,
then computation <tt>hSetPosn</tt> <I>p</I> sets the
position of <I>h</I> to the position it held at the time of the call to <tt>hGetPosn</tt>.<p>
<I>Error reporting</I>: the <tt>hSetPosn</tt> computation may fail with:
<tt>isPermissionError</tt> if a system resource limit would be exceeded.<p>
<a name="sect11.5.2"></a>
<h4>11.5.2<tt> </tt>Seeking to a new Position</h4><p>
Computation <tt>hSeek</tt> <I>hdl</I> <I>mode</I> <I>i</I> sets the position of handle
<I>hdl</I> depending on <I>mode</I>. If <I>mode</I> is:
<UL><LI>
<tt>AbsoluteSeek</tt>: the position of <I>hdl</I> is set to <I>i</I>.
<LI>
<tt>RelativeSeek</tt>: the position of <I>hdl</I> is set to offset <I>i</I> from
the current position.
<LI>
<tt>SeekFromEnd</tt>: the position of <I>hdl</I> is set to offset <I>i</I> from
the end of the file.
</UL>
The offset is given in terms of 8-bit bytes.<p>
If <I>hdl</I> 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 <tt>hIsSeekable</tt>), 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.<p>
<I>Error reporting</I>:
the <tt>hSeek</tt> computation may fail with:
<tt>isPermissionError</tt> if a system resource limit would be exceeded.<a name="Query"></a><p>
<a name="sect11.6"></a>
<h3>11.6<tt> </tt>Handle Properties</h3>
<p>
The functions
<tt>hIsOpen</tt>,
<tt>hIsClosed</tt>,
<tt>hIsReadable</tt>,
<tt>hIsWritable</tt> and
<tt>hIsSeekable
</tt>return information about the properties of a handle.
Each of these returns <tt>True</tt> if the handle has the specified property, and
<tt>False</tt> otherwise.<p>
<a name="sect11.7"></a>
<h3>11.7<tt> </tt>Text Input and Output</h3><p>
Here we define a standard set of input operations for reading
characters and strings from text files, using handles. Many of these
functions are generalizations of Prelude functions. I/O in the
Prelude generally uses <tt>stdin</tt> and <tt>stdout</tt>; here, handles are explicitly
specified by the I/O operation.<a name="hReady"></a><p>
<a name="sect11.7.1"></a>
<h4>11.7.1<tt> </tt>Checking for Input</h4>
<a name="hWaitForInput"></a>
<p>
Computation <tt>hWaitForInput</tt> <I>hdl</I> <I>t</I>
waits until input is available on handle <I>hdl</I>.
It returns <tt>True</tt> as soon as input is available on <I>hdl</I>, or <tt>False</tt> if no input is available
within <I>t</I> milliseconds.<p>
Computation <tt>hReady</tt> <I>hdl</I> indicates whether at least one item is
available for input from handle <I>hdl</I>.<p>
Computation <tt>hGetChar</tt> <I>hdl</I> reads a character from
the file or channel managed by <I>hdl</I>.<p>
Computation <tt>hGetLine</tt> <I>hdl</I> reads a line from
the file or channel managed by <I>hdl</I>, similar to <tt>getLine</tt> in the
Prelude. <p>
<I>Error reporting</I>:
the <tt>hWaitForInput</tt>, <tt>hReady</tt> and <tt>hGetChar</tt> computations may fail with:
<tt>isEOFError</tt> if the end of file has been reached.<a name="hLookahead"></a><p>
<a name="sect11.7.2"></a>
<h4>11.7.2<tt> </tt>Reading Ahead</h4>
<p>
Computation <tt>hLookAhead</tt> <I>hdl</I> returns the next character from handle
<I>hdl</I> without removing it from the input buffer, blocking until a
character is available.<p>
<I>Error reporting</I>:
the <tt>hLookahead</tt> computation may fail with:
<tt>isEOFError</tt> if the end of file has been reached.<a name="hGetContents"></a><p>
<p>
Computation <tt>hGetContents</tt> <I>hdl</I> returns the list of
characters corresponding to the unread portion of the channel or file managed
by <I>hdl</I>, which is made semi-closed.<p>
<I>Error reporting</I>:
the <tt>hGetContents</tt> computation may fail with:
<tt>isEOFError</tt> if the end of file has been reached.<p>
Computation <tt>hPutChar</tt> <I>hdl</I> <I>c</I> writes the character <I>c</I> to the file
or channel managed by <I>hdl</I>. Characters may be buffered if buffering
is enabled for <I>hdl</I>.<p>
Computation <tt>hPutStr</tt> <I>hdl</I> <I>s</I> writes the string
<I>s</I> to the file or channel managed by <I>hdl</I>.<p>
Computation <tt>hPrint</tt> <I>hdl</I> <I>t</I> writes the string representation of <I>t
</I>given by the <tt>shows</tt> function to the file or channel managed by <I>hdl</I> and appends a newline.<p>
<I>Error reporting</I>:
the <tt>hPutChar</tt>, <tt>hPutStr</tt> and <tt>hPrint</tt> computations may fail with:
<tt>isFull</tt>-<tt>Error</tt> if the device is full;
or <tt>isPermissionError</tt> if another system resource limit would be exceeded.<p>
<a name="sect11.8"></a>
<h3>11.8<tt> </tt>Examples</h3><p>
Here are some simple examples to illustrate Haskell I/O.<p>
<a name="sect11.8.1"></a>
<h4>11.8.1<tt> </tt>Summing Two Numbers</h4><p>
This program reads and sums two <tt>Integer</tt>s.
<tt><br>
<br>
import IO<br>
<br>
main = do<br>
hSetBuffering stdout NoBuffering <br>
putStr "Enter an integer: " <br>
x1 <- readNum <br>
putStr "Enter another integer: " <br>
x2 <- readNum <br>
putStr ("Their sum is " ++ show (x1+x2) ++ "\n")<br>
where readNum :: IO Integer<br>
readNum = do { line <- getLine; readIO line }<br>
<br>
<p>
</tt><a name="sect11.8.2"></a>
<h4>11.8.2<tt> </tt>Copying Files</h4><p>
A simple program to create a copy of a file, with all lower-case
characters translated to upper-case. This program will not allow a
file to be copied to itself. This version uses character-level I/O.
Note that exactly two arguments must be supplied to the program.
<tt><br>
<br>
import IO<br>
import System<br>
<br>
main = do <br>
[f1,f2] <- getArgs<br>
h1 <- openFile f1 ReadMode <br>
h2 <- openFile f2 WriteMode <br>
copyFile h1 h2 <br>
hClose h1 <br>
hClose h2<br>
<br>
copyFile h1 h2 = do<br>
eof <- hIsEOF h1<br>
if eof then return () else<br>
do<br>
c <- hGetChar h1<br>
hPutChar h2 (toUpper c) <br>
copyFile h1 h2<br>
<br>
<p>
</tt>An equivalent but much shorter version, using string I/O is:
<tt><br>
<br>
import System<br>
<br>
main = do<br>
[f1,f2] <- getArgs<br>
s <- readFile f1<br>
writeFile f2 (map toUpper s)<br>
<br>
<p>
<hr><i>The Haskell 98 Library Report</i><br><a href="index.html">top</a> | <a href="monad.html">back</a> | <a href="directory.html">next</a> | <a href="libindex.html">contents</a> <br><font size=2>1 February, 1999</font>
</tt>
|