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