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