mark System.IO.openTempFile as non-portable in haddocks
[haskell-directory.git] / System / IO.hs
1 {-# OPTIONS_GHC -fno-implicit-prelude #-}
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     -- ** Standard handles
29
30     -- | Three handles are allocated during program initialisation,
31     -- and are initially open.
32
33     stdin, stdout, stderr,   -- :: Handle
34
35     -- * Opening and closing files
36
37     -- ** Opening files
38
39     withFile,
40     openFile,                  -- :: FilePath -> IOMode -> IO Handle
41     IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),
42
43     -- ** Closing files
44
45     hClose,                    -- :: Handle -> IO ()
46
47     -- ** Special cases
48
49     -- | These functions are also exported by the "Prelude".
50
51     readFile,                  -- :: FilePath -> IO String
52     writeFile,                 -- :: FilePath -> String -> IO ()
53     appendFile,                -- :: FilePath -> String -> IO ()
54
55     -- ** File locking
56
57     -- $locking
58
59     -- * Operations on handles
60
61     -- ** Determining and changing the size of a file
62
63     hFileSize,                 -- :: Handle -> IO Integer
64 #ifdef __GLASGOW_HASKELL__
65     hSetFileSize,              -- :: Handle -> Integer -> IO ()
66 #endif
67
68     -- ** Detecting the end of input
69
70     hIsEOF,                    -- :: Handle -> IO Bool
71     isEOF,                     -- :: IO Bool
72
73     -- ** Buffering operations
74
75     BufferMode(NoBuffering,LineBuffering,BlockBuffering),
76     hSetBuffering,             -- :: Handle -> BufferMode -> IO ()
77     hGetBuffering,             -- :: Handle -> IO BufferMode
78     hFlush,                    -- :: Handle -> IO ()
79
80     -- ** Repositioning handles
81
82     hGetPosn,                  -- :: Handle -> IO HandlePosn
83     hSetPosn,                  -- :: HandlePosn -> IO ()
84     HandlePosn,                -- abstract, instance of: Eq, Show.
85
86     hSeek,                     -- :: Handle -> SeekMode -> Integer -> IO ()
87     SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),
88 #if !defined(__NHC__)
89     hTell,                     -- :: Handle -> IO Integer
90 #endif
91
92     -- ** Handle properties
93
94     hIsOpen, hIsClosed,        -- :: Handle -> IO Bool
95     hIsReadable, hIsWritable,  -- :: Handle -> IO Bool
96     hIsSeekable,               -- :: Handle -> IO Bool
97
98     -- ** Terminal operations
99
100 #if !defined(__NHC__)
101     hIsTerminalDevice,          -- :: Handle -> IO Bool
102
103     hSetEcho,                   -- :: Handle -> Bool -> IO ()
104     hGetEcho,                   -- :: Handle -> IO Bool
105 #endif
106
107     -- ** Showing handle state
108
109 #ifdef __GLASGOW_HASKELL__
110     hShow,                      -- :: Handle -> IO String
111 #endif
112
113     -- * Text input and output
114
115     -- ** Text input
116
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]
123
124     -- ** Text output
125
126     hPutChar,                  -- :: Handle -> Char -> IO ()
127     hPutStr,                   -- :: Handle -> [Char] -> IO ()
128     hPutStrLn,                 -- :: Handle -> [Char] -> IO ()
129     hPrint,                    -- :: Show a => Handle -> a -> IO ()
130
131     -- ** Special cases for standard input and output
132
133     -- | These functions are also exported by the "Prelude".
134
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
145
146     -- * Binary input and output
147
148     withBinaryFile,
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
156 #endif
157
158     -- * Temporary files (not portable: GHC only)
159
160 #ifdef __GLASGOW_HASKELL__
161     openTempFile,
162     openBinaryTempFile,
163 #endif
164   ) where
165
166 #ifdef __GLASGOW_HASKELL__
167 import GHC.Base
168 import GHC.IOBase       -- Together these four Prelude modules define
169 import GHC.Handle       -- all the stuff exported by IO for the GHC version
170 import GHC.IO
171 import GHC.Exception
172 import GHC.Num
173 import GHC.Read
174 import GHC.Show
175 #endif
176
177 #ifdef __HUGS__
178 import Hugs.IO
179 import Hugs.IOExts
180 import Hugs.IORef
181 import Hugs.Prelude     ( throw, Exception(NonTermination) )
182 import Control.Exception ( bracket )
183 import System.IO.Unsafe ( unsafeInterleaveIO )
184 #endif
185
186 #ifdef __NHC__
187 import IO
188   ( Handle ()
189   , HandlePosn ()
190   , IOMode (ReadMode,WriteMode,AppendMode,ReadWriteMode)
191   , BufferMode (NoBuffering,LineBuffering,BlockBuffering)
192   , SeekMode (AbsoluteSeek,RelativeSeek,SeekFromEnd)
193   , stdin, stdout, stderr
194   , openFile                  -- :: FilePath -> IOMode -> IO Handle
195   , hClose                    -- :: Handle -> IO ()
196   , hFileSize                 -- :: Handle -> IO Integer
197   , hIsEOF                    -- :: Handle -> IO Bool
198   , isEOF                     -- :: IO Bool
199   , hSetBuffering             -- :: Handle -> BufferMode -> IO ()
200   , hGetBuffering             -- :: Handle -> IO BufferMode
201   , hFlush                    -- :: Handle -> IO ()
202   , hGetPosn                  -- :: Handle -> IO HandlePosn
203   , hSetPosn                  -- :: HandlePosn -> IO ()
204   , hSeek                     -- :: Handle -> SeekMode -> Integer -> IO ()
205   , hWaitForInput             -- :: Handle -> Int -> IO Bool
206   , hGetChar                  -- :: Handle -> IO Char
207   , hGetLine                  -- :: Handle -> IO [Char]
208   , hLookAhead                -- :: Handle -> IO Char
209   , hGetContents              -- :: Handle -> IO [Char]
210   , hPutChar                  -- :: Handle -> Char -> IO ()
211   , hPutStr                   -- :: Handle -> [Char] -> IO ()
212   , hPutStrLn                 -- :: Handle -> [Char] -> IO ()
213   , hPrint                    -- :: Handle -> [Char] -> IO ()
214   , hReady                    -- :: Handle -> [Char] -> IO ()
215   , hIsOpen, hIsClosed        -- :: Handle -> IO Bool
216   , hIsReadable, hIsWritable  -- :: Handle -> IO Bool
217   , hIsSeekable               -- :: Handle -> IO Bool
218   , bracket
219
220   , IO ()
221   , FilePath                  -- :: String
222   )
223 import NHC.IOExtras (fixIO, hPutBuf, hGetBuf)
224 import NHC.FFI (Ptr)
225 #endif
226
227 -- -----------------------------------------------------------------------------
228 -- Standard IO
229
230 #ifdef __GLASGOW_HASKELL__
231 -- | Write a character to the standard output device
232 -- (same as 'hPutChar' 'stdout').
233
234 putChar         :: Char -> IO ()
235 putChar c       =  hPutChar stdout c
236
237 -- | Write a string to the standard output device
238 -- (same as 'hPutStr' 'stdout').
239
240 putStr          :: String -> IO ()
241 putStr s        =  hPutStr stdout s
242
243 -- | The same as 'putStr', but adds a newline character.
244
245 putStrLn        :: String -> IO ()
246 putStrLn s      =  do putStr s
247                       putChar '\n'
248
249 -- | The 'print' function outputs a value of any printable type to the
250 -- standard output device.
251 -- Printable types are those that are instances of class 'Show'; 'print'
252 -- converts values to strings for output using the 'show' operation and
253 -- adds a newline.
254 --
255 -- For example, a program to print the first 20 integers and their
256 -- powers of 2 could be written as:
257 --
258 -- > main = print ([(n, 2^n) | n <- [0..19]])
259
260 print           :: Show a => a -> IO ()
261 print x         =  putStrLn (show x)
262
263 -- | Read a character from the standard input device
264 -- (same as 'hGetChar' 'stdin').
265
266 getChar         :: IO Char
267 getChar         =  hGetChar stdin
268
269 -- | Read a line from the standard input device
270 -- (same as 'hGetLine' 'stdin').
271
272 getLine         :: IO String
273 getLine         =  hGetLine stdin
274
275 -- | The 'getContents' operation returns all user input as a single string,
276 -- which is read lazily as it is needed
277 -- (same as 'hGetContents' 'stdin').
278
279 getContents     :: IO String
280 getContents     =  hGetContents stdin
281
282 -- | The 'interact' function takes a function of type @String->String@
283 -- as its argument.  The entire input from the standard input device is
284 -- passed to this function as its argument, and the resulting string is
285 -- output on the standard output device.
286
287 interact        ::  (String -> String) -> IO ()
288 interact f      =   do s <- getContents
289                        putStr (f s)
290
291 -- | The 'readFile' function reads a file and
292 -- returns the contents of the file as a string.
293 -- The file is read lazily, on demand, as with 'getContents'.
294
295 readFile        :: FilePath -> IO String
296 readFile name   =  openFile name ReadMode >>= hGetContents
297
298 -- | The computation 'writeFile' @file str@ function writes the string @str@,
299 -- to the file @file@.
300 writeFile :: FilePath -> String -> IO ()
301 writeFile f txt = withFile f WriteMode (\ hdl -> hPutStr hdl txt)
302
303 -- | The computation 'appendFile' @file str@ function appends the string @str@,
304 -- to the file @file@.
305 --
306 -- Note that 'writeFile' and 'appendFile' write a literal string
307 -- to a file.  To write a value of any printable type, as with 'print',
308 -- use the 'show' function to convert the value to a string first.
309 --
310 -- > main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
311
312 appendFile      :: FilePath -> String -> IO ()
313 appendFile f txt = withFile f AppendMode (\ hdl -> hPutStr hdl txt)
314
315 -- | The 'readLn' function combines 'getLine' and 'readIO'.
316
317 readLn          :: Read a => IO a
318 readLn          =  do l <- getLine
319                       r <- readIO l
320                       return r
321
322 -- | The 'readIO' function is similar to 'read' except that it signals
323 -- parse failure to the 'IO' monad instead of terminating the program.
324
325 readIO          :: Read a => String -> IO a
326 readIO s        =  case (do { (x,t) <- reads s ;
327                               ("","") <- lex t ;
328                               return x }) of
329                         [x]    -> return x
330                         []     -> ioError (userError "Prelude.readIO: no parse")
331                         _      -> ioError (userError "Prelude.readIO: ambiguous parse")
332 #endif  /* __GLASGOW_HASKELL__ */
333
334 #ifndef __NHC__
335 -- | Computation 'hReady' @hdl@ indicates whether at least one item is
336 -- available for input from handle @hdl@.
337 -- 
338 -- This operation may fail with:
339 --
340 --  * 'System.IO.Error.isEOFError' if the end of file has been reached.
341
342 hReady          :: Handle -> IO Bool
343 hReady h        =  hWaitForInput h 0
344
345 -- | The same as 'hPutStr', but adds a newline character.
346
347 hPutStrLn       :: Handle -> String -> IO ()
348 hPutStrLn hndl str = do
349  hPutStr  hndl str
350  hPutChar hndl '\n'
351
352 -- | Computation 'hPrint' @hdl t@ writes the string representation of @t@
353 -- given by the 'shows' function to the file or channel managed by @hdl@
354 -- and appends a newline.
355 --
356 -- This operation may fail with:
357 --
358 --  * 'System.IO.Error.isFullError' if the device is full; or
359 --
360 --  * 'System.IO.Error.isPermissionError' if another system resource limit would be exceeded.
361
362 hPrint          :: Show a => Handle -> a -> IO ()
363 hPrint hdl      =  hPutStrLn hdl . show
364 #endif /* !__NHC__ */
365
366 -- | @'withFile' name mode act@ opens a file using 'openFile' and passes
367 -- the resulting handle to the computation @act@.  The handle will be
368 -- closed on exit from 'withFile', whether by normal termination or by
369 -- raising an exception.
370 withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
371 withFile name mode = bracket (openFile name mode) hClose
372
373 -- | @'withBinaryFile' name mode act@ opens a file using 'openBinaryFile'
374 -- and passes the resulting handle to the computation @act@.  The handle
375 -- will be closed on exit from 'withBinaryFile', whether by normal
376 -- termination or by raising an exception.
377 withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
378 withBinaryFile name mode = bracket (openBinaryFile name mode) hClose
379
380 -- ---------------------------------------------------------------------------
381 -- fixIO
382
383 #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__)
384 fixIO :: (a -> IO a) -> IO a
385 fixIO k = do
386     ref <- newIORef (throw NonTermination)
387     ans <- unsafeInterleaveIO (readIORef ref)
388     result <- k ans
389     writeIORef ref result
390     return result
391
392 -- NOTE: we do our own explicit black holing here, because GHC's lazy
393 -- blackholing isn't enough.  In an infinite loop, GHC may run the IO
394 -- computation a few times before it notices the loop, which is wrong.
395 #endif
396
397 #if defined(__NHC__)
398 -- Assume a unix platform, where text and binary I/O are identical.
399 openBinaryFile = openFile
400 hSetBinaryMode _ _ = return ()
401 #endif
402
403 -- $locking
404 -- Implementations should enforce as far as possible, at least locally to the
405 -- Haskell process, multiple-reader single-writer locking on files.
406 -- That is, /there may either be many handles on the same file which manage
407 -- input, or just one handle on the file which manages output/.  If any
408 -- open or semi-closed handle is managing a file for output, no new
409 -- handle can be allocated for that file.  If any open or semi-closed
410 -- handle is managing a file for input, new handles can only be allocated
411 -- if they do not manage output.  Whether two files are the same is
412 -- implementation-dependent, but they should normally be the same if they
413 -- have the same absolute path name and neither has been renamed, for
414 -- example.
415 --
416 -- /Warning/: the 'readFile' operation holds a semi-closed handle on
417 -- the file until the entire contents of the file have been consumed.
418 -- It follows that an attempt to write to a file (using 'writeFile', for
419 -- example) that was earlier opened by 'readFile' will usually result in
420 -- failure with 'System.IO.Error.isAlreadyInUseError'.
421
422 -- -----------------------------------------------------------------------------
423 -- Utils
424
425 #ifdef __GLASGOW_HASKELL__
426 -- Copied here to avoid recursive dependency with Control.Exception
427 bracket 
428         :: IO a         -- ^ computation to run first (\"acquire resource\")
429         -> (a -> IO b)  -- ^ computation to run last (\"release resource\")
430         -> (a -> IO c)  -- ^ computation to run in-between
431         -> IO c         -- returns the value from the in-between computation
432 bracket before after thing =
433   block (do
434     a <- before 
435     r <- catchException
436            (unblock (thing a))
437            (\e -> do { after a; throw e })
438     after a
439     return r
440  )
441 #endif