1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
2 -----------------------------------------------------------------------------
5 -- Copyright : (c) The University of Glasgow 2001
6 -- License : BSD-style (see the file libraries/base/LICENSE)
8 -- Maintainer : libraries@haskell.org
10 -- Portability : portable
12 -- The standard IO library.
14 -----------------------------------------------------------------------------
19 IO, -- instance MonadFix
20 fixIO, -- :: (a -> IO a) -> IO a
22 -- * Files and handles
24 FilePath, -- :: String
26 Handle, -- abstract, instance of: Eq, Show.
28 -- ** Standard handles
30 -- | Three handles are allocated during program initialisation,
31 -- and are initially open.
33 stdin, stdout, stderr, -- :: Handle
35 -- * Opening and closing files
40 openFile, -- :: FilePath -> IOMode -> IO Handle
41 IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),
45 hClose, -- :: Handle -> IO ()
49 -- | These functions are also exported by the "Prelude".
51 readFile, -- :: FilePath -> IO String
52 writeFile, -- :: FilePath -> String -> IO ()
53 appendFile, -- :: FilePath -> String -> IO ()
59 -- * Operations on handles
61 -- ** Determining and changing the size of a file
63 hFileSize, -- :: Handle -> IO Integer
64 #ifdef __GLASGOW_HASKELL__
65 hSetFileSize, -- :: Handle -> Integer -> IO ()
68 -- ** Detecting the end of input
70 hIsEOF, -- :: Handle -> IO Bool
73 -- ** Buffering operations
75 BufferMode(NoBuffering,LineBuffering,BlockBuffering),
76 hSetBuffering, -- :: Handle -> BufferMode -> IO ()
77 hGetBuffering, -- :: Handle -> IO BufferMode
78 hFlush, -- :: Handle -> IO ()
80 -- ** Repositioning handles
82 hGetPosn, -- :: Handle -> IO HandlePosn
83 hSetPosn, -- :: HandlePosn -> IO ()
84 HandlePosn, -- abstract, instance of: Eq, Show.
86 hSeek, -- :: Handle -> SeekMode -> Integer -> IO ()
87 SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),
89 hTell, -- :: Handle -> IO Integer
92 -- ** Handle properties
94 hIsOpen, hIsClosed, -- :: Handle -> IO Bool
95 hIsReadable, hIsWritable, -- :: Handle -> IO Bool
96 hIsSeekable, -- :: Handle -> IO Bool
98 -- ** Terminal operations (not portable: GHC\/Hugs only)
100 #if !defined(__NHC__)
101 hIsTerminalDevice, -- :: Handle -> IO Bool
103 hSetEcho, -- :: Handle -> Bool -> IO ()
104 hGetEcho, -- :: Handle -> IO Bool
107 -- ** Showing handle state (not portable: GHC only)
109 #ifdef __GLASGOW_HASKELL__
110 hShow, -- :: Handle -> IO String
113 -- * Text input and output
117 hWaitForInput, -- :: Handle -> Int -> IO Bool
118 hReady, -- :: Handle -> IO Bool
119 hGetChar, -- :: Handle -> IO Char
120 hGetLine, -- :: Handle -> IO [Char]
121 hLookAhead, -- :: Handle -> IO Char
122 hGetContents, -- :: Handle -> IO [Char]
126 hPutChar, -- :: Handle -> Char -> IO ()
127 hPutStr, -- :: Handle -> [Char] -> IO ()
128 hPutStrLn, -- :: Handle -> [Char] -> IO ()
129 hPrint, -- :: Show a => Handle -> a -> IO ()
131 -- ** Special cases for standard input and output
133 -- | These functions are also exported by the "Prelude".
135 interact, -- :: (String -> String) -> IO ()
136 putChar, -- :: Char -> IO ()
137 putStr, -- :: String -> IO ()
138 putStrLn, -- :: String -> IO ()
139 print, -- :: Show a => a -> IO ()
140 getChar, -- :: IO Char
141 getLine, -- :: IO String
142 getContents, -- :: IO String
143 readIO, -- :: Read a => String -> IO a
144 readLn, -- :: Read a => IO a
146 -- * Binary input and output
149 openBinaryFile, -- :: FilePath -> IOMode -> IO Handle
150 hSetBinaryMode, -- :: Handle -> Bool -> IO ()
151 hPutBuf, -- :: Handle -> Ptr a -> Int -> IO ()
152 hGetBuf, -- :: Handle -> Ptr a -> Int -> IO Int
153 #if !defined(__NHC__) && !defined(__HUGS__)
154 hPutBufNonBlocking, -- :: Handle -> Ptr a -> Int -> IO Int
155 hGetBufNonBlocking, -- :: Handle -> Ptr a -> Int -> IO Int
162 openTempFileWithDefaultPermissions,
163 openBinaryTempFileWithDefaultPermissions,
165 #if !defined(__NHC__) && !defined(__HUGS__)
166 -- * Unicode encoding\/decoding
168 -- | A text-mode 'Handle' has an associated 'TextEncoding', which
169 -- is used to decode bytes into Unicode characters when reading,
170 -- and encode Unicode characters into bytes when writing.
172 -- The default 'TextEncoding' is the same as the default encoding
173 -- on your system, which is also available as 'localeEncoding'.
174 -- (GHC note: on Windows, we currently do not support double-byte
175 -- encodings; if the console\'s code page is unsupported, then
176 -- 'localeEncoding' will be 'latin1'.)
178 -- Encoding and decoding errors are always detected and reported,
179 -- except during lazy I/O ('hGetContents', 'getContents', and
180 -- 'readFile'), where a decoding error merely results in
181 -- termination of the character stream, as with other I/O errors.
186 -- ** Unicode encodings
190 utf16, utf16le, utf16be,
191 utf32, utf32le, utf32be,
196 #if !defined(__NHC__) && !defined(__HUGS__)
197 -- * Newline conversion
199 -- | In Haskell, a newline is always represented by the character
200 -- '\n'. However, in files and external character streams, a
201 -- newline may be represented by another character sequence, such
204 -- A text-mode 'Handle' has an associated 'NewlineMode' that
205 -- specifies how to transate newline characters. The
206 -- 'NewlineMode' specifies the input and output translation
207 -- separately, so that for instance you can translate '\r\n'
208 -- to '\n' on input, but leave newlines as '\n' on output.
210 -- The default 'NewlineMode' for a 'Handle' is
211 -- 'nativeNewlineMode', which does no translation on Unix systems,
212 -- but translates '\r\n' to '\n' and back on Windows.
214 -- Binary-mode 'Handle's do no newline translation at all.
217 Newline(..), nativeNewline,
219 noNewlineTranslation, universalNewlineMode, nativeNewlineMode,
223 import Control.Exception.Base
229 import Foreign.C.Error
230 import Foreign.C.Types
231 import System.Posix.Internals
232 import System.Posix.Types
235 #ifdef __GLASGOW_HASKELL__
238 import GHC.IO hiding ( onException )
240 import GHC.IO.Handle.FD
241 import qualified GHC.IO.FD as FD
244 import GHC.IO.Exception ( userError )
245 import GHC.IO.Encoding
255 import System.IO.Unsafe ( unsafeInterleaveIO )
262 , IOMode (ReadMode,WriteMode,AppendMode,ReadWriteMode)
263 , BufferMode (NoBuffering,LineBuffering,BlockBuffering)
264 , SeekMode (AbsoluteSeek,RelativeSeek,SeekFromEnd)
265 , stdin, stdout, stderr
266 , openFile -- :: FilePath -> IOMode -> IO Handle
267 , hClose -- :: Handle -> IO ()
268 , hFileSize -- :: Handle -> IO Integer
269 , hIsEOF -- :: Handle -> IO Bool
270 , isEOF -- :: IO Bool
271 , hSetBuffering -- :: Handle -> BufferMode -> IO ()
272 , hGetBuffering -- :: Handle -> IO BufferMode
273 , hFlush -- :: Handle -> IO ()
274 , hGetPosn -- :: Handle -> IO HandlePosn
275 , hSetPosn -- :: HandlePosn -> IO ()
276 , hSeek -- :: Handle -> SeekMode -> Integer -> IO ()
277 , hWaitForInput -- :: Handle -> Int -> IO Bool
278 , hGetChar -- :: Handle -> IO Char
279 , hGetLine -- :: Handle -> IO [Char]
280 , hLookAhead -- :: Handle -> IO Char
281 , hGetContents -- :: Handle -> IO [Char]
282 , hPutChar -- :: Handle -> Char -> IO ()
283 , hPutStr -- :: Handle -> [Char] -> IO ()
284 , hPutStrLn -- :: Handle -> [Char] -> IO ()
285 , hPrint -- :: Handle -> [Char] -> IO ()
286 , hReady -- :: Handle -> [Char] -> IO ()
287 , hIsOpen, hIsClosed -- :: Handle -> IO Bool
288 , hIsReadable, hIsWritable -- :: Handle -> IO Bool
289 , hIsSeekable -- :: Handle -> IO Bool
293 , FilePath -- :: String
295 import NHC.IOExtras (fixIO, hPutBuf, hGetBuf)
299 -- -----------------------------------------------------------------------------
302 #ifdef __GLASGOW_HASKELL__
303 -- | Write a character to the standard output device
304 -- (same as 'hPutChar' 'stdout').
306 putChar :: Char -> IO ()
307 putChar c = hPutChar stdout c
309 -- | Write a string to the standard output device
310 -- (same as 'hPutStr' 'stdout').
312 putStr :: String -> IO ()
313 putStr s = hPutStr stdout s
315 -- | The same as 'putStr', but adds a newline character.
317 putStrLn :: String -> IO ()
318 putStrLn s = do putStr s
321 -- | The 'print' function outputs a value of any printable type to the
322 -- standard output device.
323 -- Printable types are those that are instances of class 'Show'; 'print'
324 -- converts values to strings for output using the 'show' operation and
327 -- For example, a program to print the first 20 integers and their
328 -- powers of 2 could be written as:
330 -- > main = print ([(n, 2^n) | n <- [0..19]])
332 print :: Show a => a -> IO ()
333 print x = putStrLn (show x)
335 -- | Read a character from the standard input device
336 -- (same as 'hGetChar' 'stdin').
339 getChar = hGetChar stdin
341 -- | Read a line from the standard input device
342 -- (same as 'hGetLine' 'stdin').
345 getLine = hGetLine stdin
347 -- | The 'getContents' operation returns all user input as a single string,
348 -- which is read lazily as it is needed
349 -- (same as 'hGetContents' 'stdin').
351 getContents :: IO String
352 getContents = hGetContents stdin
354 -- | The 'interact' function takes a function of type @String->String@
355 -- as its argument. The entire input from the standard input device is
356 -- passed to this function as its argument, and the resulting string is
357 -- output on the standard output device.
359 interact :: (String -> String) -> IO ()
360 interact f = do s <- getContents
363 -- | The 'readFile' function reads a file and
364 -- returns the contents of the file as a string.
365 -- The file is read lazily, on demand, as with 'getContents'.
367 readFile :: FilePath -> IO String
368 readFile name = openFile name ReadMode >>= hGetContents
370 -- | The computation 'writeFile' @file str@ function writes the string @str@,
371 -- to the file @file@.
372 writeFile :: FilePath -> String -> IO ()
373 writeFile f txt = withFile f WriteMode (\ hdl -> hPutStr hdl txt)
375 -- | The computation 'appendFile' @file str@ function appends the string @str@,
376 -- to the file @file@.
378 -- Note that 'writeFile' and 'appendFile' write a literal string
379 -- to a file. To write a value of any printable type, as with 'print',
380 -- use the 'show' function to convert the value to a string first.
382 -- > main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
384 appendFile :: FilePath -> String -> IO ()
385 appendFile f txt = withFile f AppendMode (\ hdl -> hPutStr hdl txt)
387 -- | The 'readLn' function combines 'getLine' and 'readIO'.
389 readLn :: Read a => IO a
390 readLn = do l <- getLine
394 -- | The 'readIO' function is similar to 'read' except that it signals
395 -- parse failure to the 'IO' monad instead of terminating the program.
397 readIO :: Read a => String -> IO a
398 readIO s = case (do { (x,t) <- reads s ;
402 [] -> ioError (userError "Prelude.readIO: no parse")
403 _ -> ioError (userError "Prelude.readIO: ambiguous parse")
404 #endif /* __GLASGOW_HASKELL__ */
407 -- | Computation 'hReady' @hdl@ indicates whether at least one item is
408 -- available for input from handle @hdl@.
410 -- This operation may fail with:
412 -- * 'System.IO.Error.isEOFError' if the end of file has been reached.
414 hReady :: Handle -> IO Bool
415 hReady h = hWaitForInput h 0
417 -- | The same as 'hPutStr', but adds a newline character.
419 hPutStrLn :: Handle -> String -> IO ()
420 hPutStrLn hndl str = do
424 -- | Computation 'hPrint' @hdl t@ writes the string representation of @t@
425 -- given by the 'shows' function to the file or channel managed by @hdl@
426 -- and appends a newline.
428 -- This operation may fail with:
430 -- * 'System.IO.Error.isFullError' if the device is full; or
432 -- * 'System.IO.Error.isPermissionError' if another system resource limit would be exceeded.
434 hPrint :: Show a => Handle -> a -> IO ()
435 hPrint hdl = hPutStrLn hdl . show
436 #endif /* !__NHC__ */
438 -- | @'withFile' name mode act@ opens a file using 'openFile' and passes
439 -- the resulting handle to the computation @act@. The handle will be
440 -- closed on exit from 'withFile', whether by normal termination or by
441 -- raising an exception.
442 withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
443 withFile name mode = bracket (openFile name mode) hClose
445 -- | @'withBinaryFile' name mode act@ opens a file using 'openBinaryFile'
446 -- and passes the resulting handle to the computation @act@. The handle
447 -- will be closed on exit from 'withBinaryFile', whether by normal
448 -- termination or by raising an exception.
449 withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
450 withBinaryFile name mode = bracket (openBinaryFile name mode) hClose
452 -- ---------------------------------------------------------------------------
455 #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__)
456 fixIO :: (a -> IO a) -> IO a
458 ref <- newIORef (throw NonTermination)
459 ans <- unsafeInterleaveIO (readIORef ref)
461 writeIORef ref result
464 -- NOTE: we do our own explicit black holing here, because GHC's lazy
465 -- blackholing isn't enough. In an infinite loop, GHC may run the IO
466 -- computation a few times before it notices the loop, which is wrong.
470 -- Assume a unix platform, where text and binary I/O are identical.
471 openBinaryFile = openFile
472 hSetBinaryMode _ _ = return ()
477 -- | The function creates a temporary file in ReadWrite mode.
478 -- The created file isn\'t deleted automatically, so you need to delete it manually.
480 -- The file is creates with permissions such that only the current
481 -- user can read\/write it.
483 -- With some exceptions (see below), the file will be created securely
484 -- in the sense that an attacker should not be able to cause
485 -- openTempFile to overwrite another file on the filesystem using your
486 -- credentials, by putting symbolic links (on Unix) in the place where
487 -- the temporary file is to be created. On Unix the @O_CREAT@ and
488 -- @O_EXCL@ flags are used to prevent this attack, but note that
489 -- @O_EXCL@ is sometimes not supported on NFS filesystems, so if you
490 -- rely on this behaviour it is best to use local filesystems only.
492 openTempFile :: FilePath -- ^ Directory in which to create the file
493 -> String -- ^ File name template. If the template is \"foo.ext\" then
494 -- the created file will be \"fooXXX.ext\" where XXX is some
496 -> IO (FilePath, Handle)
497 openTempFile tmp_dir template
498 = openTempFile' "openTempFile" tmp_dir template False 0o600
500 -- | Like 'openTempFile', but opens the file in binary mode. See 'openBinaryFile' for more comments.
501 openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle)
502 openBinaryTempFile tmp_dir template
503 = openTempFile' "openBinaryTempFile" tmp_dir template True 0o600
505 -- | Like 'openTempFile', but uses the default file permissions
506 openTempFileWithDefaultPermissions :: FilePath -> String
507 -> IO (FilePath, Handle)
508 openTempFileWithDefaultPermissions tmp_dir template
509 = openTempFile' "openBinaryTempFile" tmp_dir template False 0o666
511 -- | Like 'openBinaryTempFile', but uses the default file permissions
512 openBinaryTempFileWithDefaultPermissions :: FilePath -> String
513 -> IO (FilePath, Handle)
514 openBinaryTempFileWithDefaultPermissions tmp_dir template
515 = openTempFile' "openBinaryTempFile" tmp_dir template True 0o666
517 openTempFile' :: String -> FilePath -> String -> Bool -> CMode
518 -> IO (FilePath, Handle)
519 openTempFile' loc tmp_dir template binary mode = do
523 -- We split off the last extension, so we can use .foo.ext files
524 -- for temporary files (hidden on Unix OSes). Unfortunately we're
525 -- below filepath in the hierarchy here.
527 case break (== '.') $ reverse template of
528 -- First case: template contains no '.'s. Just re-reverse it.
529 (rev_suffix, "") -> (reverse rev_suffix, "")
530 -- Second case: template contains at least one '.'. Strip the
531 -- dot from the prefix and prepend it to the suffix (if we don't
532 -- do this, the unique number will get added after the '.' and
533 -- thus be part of the extension, which is wrong.)
534 (rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix)
535 -- Otherwise, something is wrong, because (break (== '.')) should
536 -- always return a pair with either the empty string or a string
537 -- beginning with '.' as the second component.
538 _ -> error "bug in System.IO.openTempFile"
541 oflags1 = rw_flags .|. o_EXCL
547 oflags = oflags1 .|. binary_flags
551 findTempName x = do h <- openFile filepath ReadWriteMode
553 #elif defined(__GLASGOW_HASKELL__)
555 fd <- withFilePath filepath $ \ f ->
561 then findTempName (x+1)
562 else ioError (errnoToIOError loc errno Nothing (Just tmp_dir))
565 (fD,fd_type) <- FD.mkFD (fromIntegral fd) ReadWriteMode Nothing{-no stat-}
569 h <- mkHandleFromFD fD fd_type filepath ReadWriteMode False{-set non-block-}
570 (Just localeEncoding)
574 h <- fdToHandle fd `onException` c_close fd
579 filename = prefix ++ show x ++ suffix
580 filepath = tmp_dir `combine` filename
582 -- XXX bits copied from System.FilePath, since that's not available here
586 | last a == pathSeparator = a ++ b
587 | otherwise = a ++ [pathSeparator] ++ b
590 fdToHandle fd = openFd (fromIntegral fd) False ReadWriteMode binary
593 -- XXX Should use filepath library
594 pathSeparator :: Char
595 #ifdef mingw32_HOST_OS
602 -- XXX Copied from GHC.Handle
603 std_flags, output_flags, rw_flags :: CInt
604 std_flags = o_NONBLOCK .|. o_NOCTTY
605 output_flags = std_flags .|. o_CREAT
606 rw_flags = output_flags .|. o_RDWR
610 foreign import ccall "getpid" c_getpid :: IO Int
614 -- Implementations should enforce as far as possible, at least locally to the
615 -- Haskell process, multiple-reader single-writer locking on files.
616 -- That is, /there may either be many handles on the same file which manage
617 -- input, or just one handle on the file which manages output/. If any
618 -- open or semi-closed handle is managing a file for output, no new
619 -- handle can be allocated for that file. If any open or semi-closed
620 -- handle is managing a file for input, new handles can only be allocated
621 -- if they do not manage output. Whether two files are the same is
622 -- implementation-dependent, but they should normally be the same if they
623 -- have the same absolute path name and neither has been renamed, for
626 -- /Warning/: the 'readFile' operation holds a semi-closed handle on
627 -- the file until the entire contents of the file have been consumed.
628 -- It follows that an attempt to write to a file (using 'writeFile', for
629 -- example) that was earlier opened by 'readFile' will usually result in
630 -- failure with 'System.IO.Error.isAlreadyInUseError'.