ab52244eff0560556fc69178957a350953c30da4
[ghc-base.git] / System / IO.hs
1 {-# LANGUAGE CPP, NoImplicitPrelude #-}
2
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  System.IO
6 -- Copyright   :  (c) The University of Glasgow 2001
7 -- License     :  BSD-style (see the file libraries/base/LICENSE)
8 -- 
9 -- Maintainer  :  libraries@haskell.org
10 -- Stability   :  stable
11 -- Portability :  portable
12 --
13 -- The standard IO library.
14 --
15 -----------------------------------------------------------------------------
16
17 module System.IO (
18     -- * The IO monad
19
20     IO,                        -- instance MonadFix
21     fixIO,                     -- :: (a -> IO a) -> IO a
22
23     -- * Files and handles
24
25     FilePath,                  -- :: String
26
27     Handle,             -- abstract, instance of: Eq, Show.
28
29     -- | GHC note: a 'Handle' will be automatically closed when the garbage
30     -- collector detects that it has become unreferenced by the program.
31     -- However, relying on this behaviour is not generally recommended:
32     -- the garbage collector is unpredictable.  If possible, use
33     -- an explicit 'hClose' to close 'Handle's when they are no longer
34     -- required.  GHC does not currently attempt to free up file
35     -- descriptors when they have run out, it is your responsibility to
36     -- ensure that this doesn't happen.
37
38     -- ** Standard handles
39
40     -- | Three handles are allocated during program initialisation,
41     -- and are initially open.
42
43     stdin, stdout, stderr,   -- :: Handle
44
45     -- * Opening and closing files
46
47     -- ** Opening files
48
49     withFile,
50     openFile,                  -- :: FilePath -> IOMode -> IO Handle
51     IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),
52
53     -- ** Closing files
54
55     hClose,                    -- :: Handle -> IO ()
56
57     -- ** Special cases
58
59     -- | These functions are also exported by the "Prelude".
60
61     readFile,                  -- :: FilePath -> IO String
62     writeFile,                 -- :: FilePath -> String -> IO ()
63     appendFile,                -- :: FilePath -> String -> IO ()
64
65     -- ** File locking
66
67     -- $locking
68
69     -- * Operations on handles
70
71     -- ** Determining and changing the size of a file
72
73     hFileSize,                 -- :: Handle -> IO Integer
74 #ifdef __GLASGOW_HASKELL__
75     hSetFileSize,              -- :: Handle -> Integer -> IO ()
76 #endif
77
78     -- ** Detecting the end of input
79
80     hIsEOF,                    -- :: Handle -> IO Bool
81     isEOF,                     -- :: IO Bool
82
83     -- ** Buffering operations
84
85     BufferMode(NoBuffering,LineBuffering,BlockBuffering),
86     hSetBuffering,             -- :: Handle -> BufferMode -> IO ()
87     hGetBuffering,             -- :: Handle -> IO BufferMode
88     hFlush,                    -- :: Handle -> IO ()
89
90     -- ** Repositioning handles
91
92     hGetPosn,                  -- :: Handle -> IO HandlePosn
93     hSetPosn,                  -- :: HandlePosn -> IO ()
94     HandlePosn,                -- abstract, instance of: Eq, Show.
95
96     hSeek,                     -- :: Handle -> SeekMode -> Integer -> IO ()
97     SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),
98 #if !defined(__NHC__)
99     hTell,                     -- :: Handle -> IO Integer
100 #endif
101
102     -- ** Handle properties
103
104     hIsOpen, hIsClosed,        -- :: Handle -> IO Bool
105     hIsReadable, hIsWritable,  -- :: Handle -> IO Bool
106     hIsSeekable,               -- :: Handle -> IO Bool
107
108     -- ** Terminal operations (not portable: GHC\/Hugs only)
109
110 #if !defined(__NHC__)
111     hIsTerminalDevice,          -- :: Handle -> IO Bool
112
113     hSetEcho,                   -- :: Handle -> Bool -> IO ()
114     hGetEcho,                   -- :: Handle -> IO Bool
115 #endif
116
117     -- ** Showing handle state (not portable: GHC only)
118
119 #ifdef __GLASGOW_HASKELL__
120     hShow,                      -- :: Handle -> IO String
121 #endif
122
123     -- * Text input and output
124
125     -- ** Text input
126
127     hWaitForInput,             -- :: Handle -> Int -> IO Bool
128     hReady,                    -- :: Handle -> IO Bool
129     hGetChar,                  -- :: Handle -> IO Char
130     hGetLine,                  -- :: Handle -> IO [Char]
131     hLookAhead,                -- :: Handle -> IO Char
132     hGetContents,              -- :: Handle -> IO [Char]
133
134     -- ** Text output
135
136     hPutChar,                  -- :: Handle -> Char -> IO ()
137     hPutStr,                   -- :: Handle -> [Char] -> IO ()
138     hPutStrLn,                 -- :: Handle -> [Char] -> IO ()
139     hPrint,                    -- :: Show a => Handle -> a -> IO ()
140
141     -- ** Special cases for standard input and output
142
143     -- | These functions are also exported by the "Prelude".
144
145     interact,                  -- :: (String -> String) -> IO ()
146     putChar,                   -- :: Char   -> IO ()
147     putStr,                    -- :: String -> IO () 
148     putStrLn,                  -- :: String -> IO ()
149     print,                     -- :: Show a => a -> IO ()
150     getChar,                   -- :: IO Char
151     getLine,                   -- :: IO String
152     getContents,               -- :: IO String
153     readIO,                    -- :: Read a => String -> IO a
154     readLn,                    -- :: Read a => IO a
155
156     -- * Binary input and output
157
158     withBinaryFile,
159     openBinaryFile,            -- :: FilePath -> IOMode -> IO Handle
160     hSetBinaryMode,            -- :: Handle -> Bool -> IO ()
161     hPutBuf,                   -- :: Handle -> Ptr a -> Int -> IO ()
162     hGetBuf,                   -- :: Handle -> Ptr a -> Int -> IO Int
163 #if !defined(__NHC__) && !defined(__HUGS__)
164     hGetBufSome,               -- :: Handle -> Ptr a -> Int -> IO Int
165     hPutBufNonBlocking,        -- :: Handle -> Ptr a -> Int -> IO Int
166     hGetBufNonBlocking,        -- :: Handle -> Ptr a -> Int -> IO Int
167 #endif
168
169     -- * Temporary files
170
171     openTempFile,
172     openBinaryTempFile,
173     openTempFileWithDefaultPermissions,
174     openBinaryTempFileWithDefaultPermissions,
175
176 #if !defined(__NHC__) && !defined(__HUGS__)
177     -- * Unicode encoding\/decoding
178
179     -- | A text-mode 'Handle' has an associated 'TextEncoding', which
180     -- is used to decode bytes into Unicode characters when reading,
181     -- and encode Unicode characters into bytes when writing.
182     --
183     -- The default 'TextEncoding' is the same as the default encoding
184     -- on your system, which is also available as 'localeEncoding'.
185     -- (GHC note: on Windows, we currently do not support double-byte
186     -- encodings; if the console\'s code page is unsupported, then
187     -- 'localeEncoding' will be 'latin1'.)
188     --
189     -- Encoding and decoding errors are always detected and reported,
190     -- except during lazy I/O ('hGetContents', 'getContents', and
191     -- 'readFile'), where a decoding error merely results in
192     -- termination of the character stream, as with other I/O errors.
193
194     hSetEncoding, 
195     hGetEncoding,
196
197     -- ** Unicode encodings
198     TextEncoding, 
199     latin1,
200     utf8, utf8_bom,
201     utf16, utf16le, utf16be,
202     utf32, utf32le, utf32be, 
203     localeEncoding,
204     mkTextEncoding,
205 #endif
206
207 #if !defined(__NHC__) && !defined(__HUGS__)
208     -- * Newline conversion
209     
210     -- | In Haskell, a newline is always represented by the character
211     -- '\n'.  However, in files and external character streams, a
212     -- newline may be represented by another character sequence, such
213     -- as '\r\n'.
214     --
215     -- A text-mode 'Handle' has an associated 'NewlineMode' that
216     -- specifies how to transate newline characters.  The
217     -- 'NewlineMode' specifies the input and output translation
218     -- separately, so that for instance you can translate '\r\n'
219     -- to '\n' on input, but leave newlines as '\n' on output.
220     --
221     -- The default 'NewlineMode' for a 'Handle' is
222     -- 'nativeNewlineMode', which does no translation on Unix systems,
223     -- but translates '\r\n' to '\n' and back on Windows.
224     --
225     -- Binary-mode 'Handle's do no newline translation at all.
226     --
227     hSetNewlineMode, 
228     Newline(..), nativeNewline, 
229     NewlineMode(..), 
230     noNewlineTranslation, universalNewlineMode, nativeNewlineMode,
231 #endif
232   ) where
233
234 import Control.Exception.Base
235
236 #ifndef __NHC__
237 import Data.Bits
238 import Data.List
239 import Data.Maybe
240 import Foreign.C.Error
241 import Foreign.C.Types
242 import System.Posix.Internals
243 import System.Posix.Types
244 #endif
245
246 #ifdef __GLASGOW_HASKELL__
247 import GHC.Base
248 import GHC.IO hiding ( bracket, onException )
249 import GHC.IO.IOMode
250 import GHC.IO.Handle.FD
251 import qualified GHC.IO.FD as FD
252 import GHC.IO.Handle
253 import GHC.IO.Handle.Text ( hGetBufSome, hPutStrLn )
254 import GHC.IORef
255 import GHC.IO.Exception ( userError )
256 import GHC.IO.Encoding
257 import GHC.Num
258 import Text.Read
259 import GHC.Show
260 #endif
261
262 #ifdef __HUGS__
263 import Hugs.IO
264 import Hugs.IOExts
265 import Hugs.IORef
266 import System.IO.Unsafe ( unsafeInterleaveIO )
267 #endif
268
269 #ifdef __NHC__
270 import IO
271   ( Handle ()
272   , HandlePosn ()
273   , IOMode (ReadMode,WriteMode,AppendMode,ReadWriteMode)
274   , BufferMode (NoBuffering,LineBuffering,BlockBuffering)
275   , SeekMode (AbsoluteSeek,RelativeSeek,SeekFromEnd)
276   , stdin, stdout, stderr
277   , openFile                  -- :: FilePath -> IOMode -> IO Handle
278   , hClose                    -- :: Handle -> IO ()
279   , hFileSize                 -- :: Handle -> IO Integer
280   , hIsEOF                    -- :: Handle -> IO Bool
281   , isEOF                     -- :: IO Bool
282   , hSetBuffering             -- :: Handle -> BufferMode -> IO ()
283   , hGetBuffering             -- :: Handle -> IO BufferMode
284   , hFlush                    -- :: Handle -> IO ()
285   , hGetPosn                  -- :: Handle -> IO HandlePosn
286   , hSetPosn                  -- :: HandlePosn -> IO ()
287   , hSeek                     -- :: Handle -> SeekMode -> Integer -> IO ()
288   , hWaitForInput             -- :: Handle -> Int -> IO Bool
289   , hGetChar                  -- :: Handle -> IO Char
290   , hGetLine                  -- :: Handle -> IO [Char]
291   , hLookAhead                -- :: Handle -> IO Char
292   , hGetContents              -- :: Handle -> IO [Char]
293   , hPutChar                  -- :: Handle -> Char -> IO ()
294   , hPutStr                   -- :: Handle -> [Char] -> IO ()
295   , hPutStrLn                 -- :: Handle -> [Char] -> IO ()
296   , hPrint                    -- :: Handle -> [Char] -> IO ()
297   , hReady                    -- :: Handle -> [Char] -> IO ()
298   , hIsOpen, hIsClosed        -- :: Handle -> IO Bool
299   , hIsReadable, hIsWritable  -- :: Handle -> IO Bool
300   , hIsSeekable               -- :: Handle -> IO Bool
301   , bracket
302
303   , IO ()
304   , FilePath                  -- :: String
305   )
306 import NHC.IOExtras (fixIO, hPutBuf, hGetBuf)
307 import NHC.FFI (Ptr)
308 #endif
309
310 -- -----------------------------------------------------------------------------
311 -- Standard IO
312
313 #ifdef __GLASGOW_HASKELL__
314 -- | Write a character to the standard output device
315 -- (same as 'hPutChar' 'stdout').
316
317 putChar         :: Char -> IO ()
318 putChar c       =  hPutChar stdout c
319
320 -- | Write a string to the standard output device
321 -- (same as 'hPutStr' 'stdout').
322
323 putStr          :: String -> IO ()
324 putStr s        =  hPutStr stdout s
325
326 -- | The same as 'putStr', but adds a newline character.
327
328 putStrLn        :: String -> IO ()
329 putStrLn s      =  hPutStrLn stdout s
330
331 -- | The 'print' function outputs a value of any printable type to the
332 -- standard output device.
333 -- Printable types are those that are instances of class 'Show'; 'print'
334 -- converts values to strings for output using the 'show' operation and
335 -- adds a newline.
336 --
337 -- For example, a program to print the first 20 integers and their
338 -- powers of 2 could be written as:
339 --
340 -- > main = print ([(n, 2^n) | n <- [0..19]])
341
342 print           :: Show a => a -> IO ()
343 print x         =  putStrLn (show x)
344
345 -- | Read a character from the standard input device
346 -- (same as 'hGetChar' 'stdin').
347
348 getChar         :: IO Char
349 getChar         =  hGetChar stdin
350
351 -- | Read a line from the standard input device
352 -- (same as 'hGetLine' 'stdin').
353
354 getLine         :: IO String
355 getLine         =  hGetLine stdin
356
357 -- | The 'getContents' operation returns all user input as a single string,
358 -- which is read lazily as it is needed
359 -- (same as 'hGetContents' 'stdin').
360
361 getContents     :: IO String
362 getContents     =  hGetContents stdin
363
364 -- | The 'interact' function takes a function of type @String->String@
365 -- as its argument.  The entire input from the standard input device is
366 -- passed to this function as its argument, and the resulting string is
367 -- output on the standard output device.
368
369 interact        ::  (String -> String) -> IO ()
370 interact f      =   do s <- getContents
371                        putStr (f s)
372
373 -- | The 'readFile' function reads a file and
374 -- returns the contents of the file as a string.
375 -- The file is read lazily, on demand, as with 'getContents'.
376
377 readFile        :: FilePath -> IO String
378 readFile name   =  openFile name ReadMode >>= hGetContents
379
380 -- | The computation 'writeFile' @file str@ function writes the string @str@,
381 -- to the file @file@.
382 writeFile :: FilePath -> String -> IO ()
383 writeFile f txt = withFile f WriteMode (\ hdl -> hPutStr hdl txt)
384
385 -- | The computation 'appendFile' @file str@ function appends the string @str@,
386 -- to the file @file@.
387 --
388 -- Note that 'writeFile' and 'appendFile' write a literal string
389 -- to a file.  To write a value of any printable type, as with 'print',
390 -- use the 'show' function to convert the value to a string first.
391 --
392 -- > main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
393
394 appendFile      :: FilePath -> String -> IO ()
395 appendFile f txt = withFile f AppendMode (\ hdl -> hPutStr hdl txt)
396
397 -- | The 'readLn' function combines 'getLine' and 'readIO'.
398
399 readLn          :: Read a => IO a
400 readLn          =  do l <- getLine
401                       r <- readIO l
402                       return r
403
404 -- | The 'readIO' function is similar to 'read' except that it signals
405 -- parse failure to the 'IO' monad instead of terminating the program.
406
407 readIO          :: Read a => String -> IO a
408 readIO s        =  case (do { (x,t) <- reads s ;
409                               ("","") <- lex t ;
410                               return x }) of
411                         [x]    -> return x
412                         []     -> ioError (userError "Prelude.readIO: no parse")
413                         _      -> ioError (userError "Prelude.readIO: ambiguous parse")
414 #endif  /* __GLASGOW_HASKELL__ */
415
416 #ifndef __NHC__
417 -- | Computation 'hReady' @hdl@ indicates whether at least one item is
418 -- available for input from handle @hdl@.
419 -- 
420 -- This operation may fail with:
421 --
422 --  * 'System.IO.Error.isEOFError' if the end of file has been reached.
423
424 hReady          :: Handle -> IO Bool
425 hReady h        =  hWaitForInput h 0
426
427 -- | Computation 'hPrint' @hdl t@ writes the string representation of @t@
428 -- given by the 'shows' function to the file or channel managed by @hdl@
429 -- and appends a newline.
430 --
431 -- This operation may fail with:
432 --
433 --  * 'System.IO.Error.isFullError' if the device is full; or
434 --
435 --  * 'System.IO.Error.isPermissionError' if another system resource limit would be exceeded.
436
437 hPrint          :: Show a => Handle -> a -> IO ()
438 hPrint hdl      =  hPutStrLn hdl . show
439 #endif /* !__NHC__ */
440
441 -- | @'withFile' name mode act@ opens a file using 'openFile' and passes
442 -- the resulting handle to the computation @act@.  The handle will be
443 -- closed on exit from 'withFile', whether by normal termination or by
444 -- raising an exception.  If closing the handle raises an exception, then
445 -- this exception will be raised by 'withFile' rather than any exception
446 -- raised by 'act'.
447 withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
448 withFile name mode = bracket (openFile name mode) hClose
449
450 -- | @'withBinaryFile' name mode act@ opens a file using 'openBinaryFile'
451 -- and passes the resulting handle to the computation @act@.  The handle
452 -- will be closed on exit from 'withBinaryFile', whether by normal
453 -- termination or by raising an exception.
454 withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
455 withBinaryFile name mode = bracket (openBinaryFile name mode) hClose
456
457 -- ---------------------------------------------------------------------------
458 -- fixIO
459
460 #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__)
461 fixIO :: (a -> IO a) -> IO a
462 fixIO k = do
463     ref <- newIORef (throw NonTermination)
464     ans <- unsafeInterleaveIO (readIORef ref)
465     result <- k ans
466     writeIORef ref result
467     return result
468
469 -- NOTE: we do our own explicit black holing here, because GHC's lazy
470 -- blackholing isn't enough.  In an infinite loop, GHC may run the IO
471 -- computation a few times before it notices the loop, which is wrong.
472 #endif
473
474 #if defined(__NHC__)
475 -- Assume a unix platform, where text and binary I/O are identical.
476 openBinaryFile = openFile
477 hSetBinaryMode _ _ = return ()
478
479 type CMode = Int
480 #endif
481
482 -- | The function creates a temporary file in ReadWrite mode.
483 -- The created file isn\'t deleted automatically, so you need to delete it manually.
484 --
485 -- The file is creates with permissions such that only the current
486 -- user can read\/write it.
487 --
488 -- With some exceptions (see below), the file will be created securely
489 -- in the sense that an attacker should not be able to cause
490 -- openTempFile to overwrite another file on the filesystem using your
491 -- credentials, by putting symbolic links (on Unix) in the place where
492 -- the temporary file is to be created.  On Unix the @O_CREAT@ and
493 -- @O_EXCL@ flags are used to prevent this attack, but note that
494 -- @O_EXCL@ is sometimes not supported on NFS filesystems, so if you
495 -- rely on this behaviour it is best to use local filesystems only.
496 --
497 openTempFile :: FilePath   -- ^ Directory in which to create the file
498              -> String     -- ^ File name template. If the template is \"foo.ext\" then
499                            -- the created file will be \"fooXXX.ext\" where XXX is some
500                            -- random number.
501              -> IO (FilePath, Handle)
502 openTempFile tmp_dir template
503     = openTempFile' "openTempFile" tmp_dir template False 0o600
504
505 -- | Like 'openTempFile', but opens the file in binary mode. See 'openBinaryFile' for more comments.
506 openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle)
507 openBinaryTempFile tmp_dir template
508     = openTempFile' "openBinaryTempFile" tmp_dir template True 0o600
509
510 -- | Like 'openTempFile', but uses the default file permissions
511 openTempFileWithDefaultPermissions :: FilePath -> String
512                                    -> IO (FilePath, Handle)
513 openTempFileWithDefaultPermissions tmp_dir template
514     = openTempFile' "openBinaryTempFile" tmp_dir template False 0o666
515
516 -- | Like 'openBinaryTempFile', but uses the default file permissions
517 openBinaryTempFileWithDefaultPermissions :: FilePath -> String
518                                          -> IO (FilePath, Handle)
519 openBinaryTempFileWithDefaultPermissions tmp_dir template
520     = openTempFile' "openBinaryTempFile" tmp_dir template True 0o666
521
522 openTempFile' :: String -> FilePath -> String -> Bool -> CMode
523               -> IO (FilePath, Handle)
524 openTempFile' loc tmp_dir template binary mode = do
525   pid <- c_getpid
526   findTempName pid
527   where
528     -- We split off the last extension, so we can use .foo.ext files
529     -- for temporary files (hidden on Unix OSes). Unfortunately we're
530     -- below filepath in the hierarchy here.
531     (prefix,suffix) =
532        case break (== '.') $ reverse template of
533          -- First case: template contains no '.'s. Just re-reverse it.
534          (rev_suffix, "")       -> (reverse rev_suffix, "")
535          -- Second case: template contains at least one '.'. Strip the
536          -- dot from the prefix and prepend it to the suffix (if we don't
537          -- do this, the unique number will get added after the '.' and
538          -- thus be part of the extension, which is wrong.)
539          (rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix)
540          -- Otherwise, something is wrong, because (break (== '.')) should
541          -- always return a pair with either the empty string or a string
542          -- beginning with '.' as the second component.
543          _                      -> error "bug in System.IO.openTempFile"
544
545 #ifndef __NHC__
546     oflags1 = rw_flags .|. o_EXCL
547
548     binary_flags
549       | binary    = o_BINARY
550       | otherwise = 0
551
552     oflags = oflags1 .|. binary_flags
553 #endif
554
555 #if defined(__NHC__)
556     findTempName x = do h <- openFile filepath ReadWriteMode
557                         return (filepath, h)
558 #elif defined(__GLASGOW_HASKELL__)
559     findTempName x = do
560       fd <- withFilePath filepath $ \ f ->
561               c_open f oflags mode
562       if fd < 0
563        then do
564          errno <- getErrno
565          if errno == eEXIST
566            then findTempName (x+1)
567            else ioError (errnoToIOError loc errno Nothing (Just tmp_dir))
568        else do
569
570          (fD,fd_type) <- FD.mkFD fd ReadWriteMode Nothing{-no stat-}
571                               False{-is_socket-} 
572                               True{-is_nonblock-}
573
574          h <- mkHandleFromFD fD fd_type filepath ReadWriteMode False{-set non-block-}
575                            (Just localeEncoding)
576
577          return (filepath, h)
578 #else
579          h <- fdToHandle fd `onException` c_close fd
580          return (filepath, h)
581 #endif
582
583       where
584         filename        = prefix ++ show x ++ suffix
585         filepath        = tmp_dir `combine` filename
586
587         -- XXX bits copied from System.FilePath, since that's not available here
588         combine a b
589                   | null b = a
590                   | null a = b
591                   | last a == pathSeparator = a ++ b
592                   | otherwise = a ++ [pathSeparator] ++ b
593
594 #if __HUGS__
595         fdToHandle fd   = openFd (fromIntegral fd) False ReadWriteMode binary
596 #endif
597
598 -- XXX Should use filepath library
599 pathSeparator :: Char
600 #ifdef mingw32_HOST_OS
601 pathSeparator = '\\'
602 #else
603 pathSeparator = '/'
604 #endif
605
606 #ifndef __NHC__
607 -- XXX Copied from GHC.Handle
608 std_flags, output_flags, rw_flags :: CInt
609 std_flags    = o_NONBLOCK   .|. o_NOCTTY
610 output_flags = std_flags    .|. o_CREAT
611 rw_flags     = output_flags .|. o_RDWR
612 #endif
613
614 #ifdef __NHC__
615 foreign import ccall "getpid" c_getpid :: IO Int
616 #endif
617
618 -- $locking
619 -- Implementations should enforce as far as possible, at least locally to the
620 -- Haskell process, multiple-reader single-writer locking on files.
621 -- 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
622 -- open or semi-closed handle is managing a file for output, no new
623 -- handle can be allocated for that file.  If any open or semi-closed
624 -- handle is managing a file for input, new handles can only be allocated
625 -- if they do not manage output.  Whether two files are the same is
626 -- implementation-dependent, but they should normally be the same if they
627 -- have the same absolute path name and neither has been renamed, for
628 -- example.
629 --
630 -- /Warning/: the 'readFile' operation holds a semi-closed handle on
631 -- the file until the entire contents of the file have been consumed.
632 -- It follows that an attempt to write to a file (using 'writeFile', for
633 -- example) that was earlier opened by 'readFile' will usually result in
634 -- failure with 'System.IO.Error.isAlreadyInUseError'.