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
164 import Control.Exception.Base
170 import Foreign.C.Error
171 import Foreign.C.String
172 import Foreign.C.Types
173 import System.Posix.Internals
176 #ifdef __GLASGOW_HASKELL__
178 import GHC.IOBase -- Together these four Prelude modules define
179 import GHC.Handle -- all the stuff exported by IO for the GHC version
191 import System.IO.Unsafe ( unsafeInterleaveIO )
198 , IOMode (ReadMode,WriteMode,AppendMode,ReadWriteMode)
199 , BufferMode (NoBuffering,LineBuffering,BlockBuffering)
200 , SeekMode (AbsoluteSeek,RelativeSeek,SeekFromEnd)
201 , stdin, stdout, stderr
202 , openFile -- :: FilePath -> IOMode -> IO Handle
203 , hClose -- :: Handle -> IO ()
204 , hFileSize -- :: Handle -> IO Integer
205 , hIsEOF -- :: Handle -> IO Bool
206 , isEOF -- :: IO Bool
207 , hSetBuffering -- :: Handle -> BufferMode -> IO ()
208 , hGetBuffering -- :: Handle -> IO BufferMode
209 , hFlush -- :: Handle -> IO ()
210 , hGetPosn -- :: Handle -> IO HandlePosn
211 , hSetPosn -- :: HandlePosn -> IO ()
212 , hSeek -- :: Handle -> SeekMode -> Integer -> IO ()
213 , hWaitForInput -- :: Handle -> Int -> IO Bool
214 , hGetChar -- :: Handle -> IO Char
215 , hGetLine -- :: Handle -> IO [Char]
216 , hLookAhead -- :: Handle -> IO Char
217 , hGetContents -- :: Handle -> IO [Char]
218 , hPutChar -- :: Handle -> Char -> IO ()
219 , hPutStr -- :: Handle -> [Char] -> IO ()
220 , hPutStrLn -- :: Handle -> [Char] -> IO ()
221 , hPrint -- :: Handle -> [Char] -> IO ()
222 , hReady -- :: Handle -> [Char] -> IO ()
223 , hIsOpen, hIsClosed -- :: Handle -> IO Bool
224 , hIsReadable, hIsWritable -- :: Handle -> IO Bool
225 , hIsSeekable -- :: Handle -> IO Bool
229 , FilePath -- :: String
231 import NHC.IOExtras (fixIO, hPutBuf, hGetBuf)
235 -- -----------------------------------------------------------------------------
238 #ifdef __GLASGOW_HASKELL__
239 -- | Write a character to the standard output device
240 -- (same as 'hPutChar' 'stdout').
242 putChar :: Char -> IO ()
243 putChar c = hPutChar stdout c
245 -- | Write a string to the standard output device
246 -- (same as 'hPutStr' 'stdout').
248 putStr :: String -> IO ()
249 putStr s = hPutStr stdout s
251 -- | The same as 'putStr', but adds a newline character.
253 putStrLn :: String -> IO ()
254 putStrLn s = do putStr s
257 -- | The 'print' function outputs a value of any printable type to the
258 -- standard output device.
259 -- Printable types are those that are instances of class 'Show'; 'print'
260 -- converts values to strings for output using the 'show' operation and
263 -- For example, a program to print the first 20 integers and their
264 -- powers of 2 could be written as:
266 -- > main = print ([(n, 2^n) | n <- [0..19]])
268 print :: Show a => a -> IO ()
269 print x = putStrLn (show x)
271 -- | Read a character from the standard input device
272 -- (same as 'hGetChar' 'stdin').
275 getChar = hGetChar stdin
277 -- | Read a line from the standard input device
278 -- (same as 'hGetLine' 'stdin').
281 getLine = hGetLine stdin
283 -- | The 'getContents' operation returns all user input as a single string,
284 -- which is read lazily as it is needed
285 -- (same as 'hGetContents' 'stdin').
287 getContents :: IO String
288 getContents = hGetContents stdin
290 -- | The 'interact' function takes a function of type @String->String@
291 -- as its argument. The entire input from the standard input device is
292 -- passed to this function as its argument, and the resulting string is
293 -- output on the standard output device.
295 interact :: (String -> String) -> IO ()
296 interact f = do s <- getContents
299 -- | The 'readFile' function reads a file and
300 -- returns the contents of the file as a string.
301 -- The file is read lazily, on demand, as with 'getContents'.
303 readFile :: FilePath -> IO String
304 readFile name = openFile name ReadMode >>= hGetContents
306 -- | The computation 'writeFile' @file str@ function writes the string @str@,
307 -- to the file @file@.
308 writeFile :: FilePath -> String -> IO ()
309 writeFile f txt = withFile f WriteMode (\ hdl -> hPutStr hdl txt)
311 -- | The computation 'appendFile' @file str@ function appends the string @str@,
312 -- to the file @file@.
314 -- Note that 'writeFile' and 'appendFile' write a literal string
315 -- to a file. To write a value of any printable type, as with 'print',
316 -- use the 'show' function to convert the value to a string first.
318 -- > main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
320 appendFile :: FilePath -> String -> IO ()
321 appendFile f txt = withFile f AppendMode (\ hdl -> hPutStr hdl txt)
323 -- | The 'readLn' function combines 'getLine' and 'readIO'.
325 readLn :: Read a => IO a
326 readLn = do l <- getLine
330 -- | The 'readIO' function is similar to 'read' except that it signals
331 -- parse failure to the 'IO' monad instead of terminating the program.
333 readIO :: Read a => String -> IO a
334 readIO s = case (do { (x,t) <- reads s ;
338 [] -> ioError (userError "Prelude.readIO: no parse")
339 _ -> ioError (userError "Prelude.readIO: ambiguous parse")
340 #endif /* __GLASGOW_HASKELL__ */
343 -- | Computation 'hReady' @hdl@ indicates whether at least one item is
344 -- available for input from handle @hdl@.
346 -- This operation may fail with:
348 -- * 'System.IO.Error.isEOFError' if the end of file has been reached.
350 hReady :: Handle -> IO Bool
351 hReady h = hWaitForInput h 0
353 -- | The same as 'hPutStr', but adds a newline character.
355 hPutStrLn :: Handle -> String -> IO ()
356 hPutStrLn hndl str = do
360 -- | Computation 'hPrint' @hdl t@ writes the string representation of @t@
361 -- given by the 'shows' function to the file or channel managed by @hdl@
362 -- and appends a newline.
364 -- This operation may fail with:
366 -- * 'System.IO.Error.isFullError' if the device is full; or
368 -- * 'System.IO.Error.isPermissionError' if another system resource limit would be exceeded.
370 hPrint :: Show a => Handle -> a -> IO ()
371 hPrint hdl = hPutStrLn hdl . show
372 #endif /* !__NHC__ */
374 -- | @'withFile' name mode act@ opens a file using 'openFile' and passes
375 -- the resulting handle to the computation @act@. The handle will be
376 -- closed on exit from 'withFile', whether by normal termination or by
377 -- raising an exception.
378 withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
379 withFile name mode = bracket (openFile name mode) hClose
381 -- | @'withBinaryFile' name mode act@ opens a file using 'openBinaryFile'
382 -- and passes the resulting handle to the computation @act@. The handle
383 -- will be closed on exit from 'withBinaryFile', whether by normal
384 -- termination or by raising an exception.
385 withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
386 withBinaryFile name mode = bracket (openBinaryFile name mode) hClose
388 -- ---------------------------------------------------------------------------
391 #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__)
392 fixIO :: (a -> IO a) -> IO a
394 ref <- newIORef (throw NonTermination)
395 ans <- unsafeInterleaveIO (readIORef ref)
397 writeIORef ref result
400 -- NOTE: we do our own explicit black holing here, because GHC's lazy
401 -- blackholing isn't enough. In an infinite loop, GHC may run the IO
402 -- computation a few times before it notices the loop, which is wrong.
406 -- Assume a unix platform, where text and binary I/O are identical.
407 openBinaryFile = openFile
408 hSetBinaryMode _ _ = return ()
411 -- | The function creates a temporary file in ReadWrite mode.
412 -- The created file isn\'t deleted automatically, so you need to delete it manually.
414 -- The file is creates with permissions such that only the current
415 -- user can read\/write it.
417 -- With some exceptions (see below), the file will be created securely
418 -- in the sense that an attacker should not be able to cause
419 -- openTempFile to overwrite another file on the filesystem using your
420 -- credentials, by putting symbolic links (on Unix) in the place where
421 -- the temporary file is to be created. On Unix the @O_CREAT@ and
422 -- @O_EXCL@ flags are used to prevent this attack, but note that
423 -- @O_EXCL@ is sometimes not supported on NFS filesystems, so if you
424 -- rely on this behaviour it is best to use local filesystems only.
426 openTempFile :: FilePath -- ^ Directory in which to create the file
427 -> String -- ^ File name template. If the template is \"foo.ext\" then
428 -- the created file will be \"fooXXX.ext\" where XXX is some
430 -> IO (FilePath, Handle)
431 openTempFile tmp_dir template = openTempFile' "openTempFile" tmp_dir template False
433 -- | Like 'openTempFile', but opens the file in binary mode. See 'openBinaryFile' for more comments.
434 openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle)
435 openBinaryTempFile tmp_dir template = openTempFile' "openBinaryTempFile" tmp_dir template True
437 openTempFile' :: String -> FilePath -> String -> Bool -> IO (FilePath, Handle)
438 openTempFile' loc tmp_dir template binary = do
442 -- We split off the last extension, so we can use .foo.ext files
443 -- for temporary files (hidden on Unix OSes). Unfortunately we're
444 -- below filepath in the hierarchy here.
446 case break (== '.') $ reverse template of
447 -- First case: template contains no '.'s. Just re-reverse it.
448 (rev_suffix, "") -> (reverse rev_suffix, "")
449 -- Second case: template contains at least one '.'. Strip the
450 -- dot from the prefix and prepend it to the suffix (if we don't
451 -- do this, the unique number will get added after the '.' and
452 -- thus be part of the extension, which is wrong.)
453 (rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix)
454 -- Otherwise, something is wrong, because (break (== '.')) should
455 -- always return a pair with either the empty string or a string
456 -- beginning with '.' as the second component.
457 _ -> error "bug in System.IO.openTempFile"
460 oflags1 = rw_flags .|. o_EXCL
466 oflags = oflags1 .|. binary_flags
470 findTempName x = do h <- openFile filepath ReadWriteMode
474 fd <- withCString filepath $ \ f ->
475 c_open f oflags 0o600
480 then findTempName (x+1)
481 else ioError (errnoToIOError loc errno Nothing (Just tmp_dir))
483 -- XXX We want to tell fdToHandle what the filepath is,
484 -- as any exceptions etc will only be able to report the
486 h <- fdToHandle fd `onException` c_close fd
490 filename = prefix ++ show x ++ suffix
491 filepath = tmp_dir `combine` filename
493 -- XXX bits copied from System.FilePath, since that's not available here
497 | last a == pathSeparator = a ++ b
498 | otherwise = a ++ [pathSeparator] ++ b
501 fdToHandle fd = openFd (fromIntegral fd) False ReadWriteMode binary
504 -- XXX Should use filepath library
505 pathSeparator :: Char
506 #ifdef mingw32_HOST_OS
513 -- XXX Copied from GHC.Handle
514 std_flags, output_flags, rw_flags :: CInt
515 std_flags = o_NONBLOCK .|. o_NOCTTY
516 output_flags = std_flags .|. o_CREAT
517 rw_flags = output_flags .|. o_RDWR
521 foreign import ccall "getpid" c_getpid :: IO Int
525 -- Implementations should enforce as far as possible, at least locally to the
526 -- Haskell process, multiple-reader single-writer locking on files.
527 -- That is, /there may either be many handles on the same file which manage
528 -- input, or just one handle on the file which manages output/. If any
529 -- open or semi-closed handle is managing a file for output, no new
530 -- handle can be allocated for that file. If any open or semi-closed
531 -- handle is managing a file for input, new handles can only be allocated
532 -- if they do not manage output. Whether two files are the same is
533 -- implementation-dependent, but they should normally be the same if they
534 -- have the same absolute path name and neither has been renamed, for
537 -- /Warning/: the 'readFile' operation holds a semi-closed handle on
538 -- the file until the entire contents of the file have been consumed.
539 -- It follows that an attempt to write to a file (using 'writeFile', for
540 -- example) that was earlier opened by 'readFile' will usually result in
541 -- failure with 'System.IO.Error.isAlreadyInUseError'.