23e7428544dfcacf39d450350ec32c629271debb
[ghc-base.git] / System / IO.hs
1 {-# OPTIONS -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   :  provisional
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     openFile,                  -- :: FilePath -> IOMode -> IO Handle
40     IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),
41
42     -- ** Closing files
43
44     hClose,                    -- :: Handle -> IO ()
45
46     -- ** Special cases
47
48     -- | These functions are also exported by the "Prelude".
49
50     readFile,                  -- :: FilePath -> IO String
51     writeFile,                 -- :: FilePath -> String -> IO ()
52     appendFile,                -- :: FilePath -> String -> IO ()
53
54     -- ** File locking
55
56     -- $locking
57
58     -- * Operations on handles
59
60     -- ** Determining the size of a file
61
62     hFileSize,                 -- :: Handle -> IO Integer
63
64     -- ** Detecting the end of input
65
66     hIsEOF,                    -- :: Handle -> IO Bool
67     isEOF,                     -- :: IO Bool
68
69     -- ** Buffering operations
70
71     BufferMode(NoBuffering,LineBuffering,BlockBuffering),
72     hSetBuffering,             -- :: Handle -> BufferMode -> IO ()
73     hGetBuffering,             -- :: Handle -> IO BufferMode
74     hFlush,                    -- :: Handle -> IO ()
75
76     -- ** Repositioning handles
77
78     hGetPosn,                  -- :: Handle -> IO HandlePosn
79     hSetPosn,                  -- :: HandlePosn -> IO ()
80     HandlePosn,                -- abstract, instance of: Eq, Show.
81
82     hSeek,                     -- :: Handle -> SeekMode -> Integer -> IO ()
83     SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),
84 #if !defined(__NHC__)
85     hTell,                     -- :: Handle -> IO Integer
86 #endif
87
88     -- ** Handle properties
89
90     hIsOpen, hIsClosed,        -- :: Handle -> IO Bool
91     hIsReadable, hIsWritable,  -- :: Handle -> IO Bool
92     hIsSeekable,               -- :: Handle -> IO Bool
93
94     -- ** Terminal operations
95
96 #if !defined(__HUGS__) && !defined(__NHC__)
97     hIsTerminalDevice,          -- :: Handle -> IO Bool
98
99     hSetEcho,                   -- :: Handle -> Bool -> IO ()
100     hGetEcho,                   -- :: Handle -> IO Bool
101 #endif
102
103     -- ** Showing handle state
104
105 #ifdef __GLASGOW_HASKELL__
106     hShow,                      -- :: Handle -> IO String
107 #endif
108
109     -- * Text input and output
110
111     -- ** Text input
112
113     hWaitForInput,             -- :: Handle -> Int -> IO Bool
114     hReady,                    -- :: Handle -> IO Bool
115     hGetChar,                  -- :: Handle -> IO Char
116     hGetLine,                  -- :: Handle -> IO [Char]
117     hLookAhead,                -- :: Handle -> IO Char
118     hGetContents,              -- :: Handle -> IO [Char]
119
120     -- ** Text output
121
122     hPutChar,                  -- :: Handle -> Char -> IO ()
123     hPutStr,                   -- :: Handle -> [Char] -> IO ()
124     hPutStrLn,                 -- :: Handle -> [Char] -> IO ()
125     hPrint,                    -- :: Show a => Handle -> a -> IO ()
126
127     -- ** Special cases for standard input and output
128
129     -- | These functions are also exported by the "Prelude".
130
131     interact,                  -- :: (String -> String) -> IO ()
132     putChar,                   -- :: Char   -> IO ()
133     putStr,                    -- :: String -> IO () 
134     putStrLn,                  -- :: String -> IO ()
135     print,                     -- :: Show a => a -> IO ()
136     getChar,                   -- :: IO Char
137     getLine,                   -- :: IO String
138     getContents,               -- :: IO String
139     readIO,                    -- :: Read a => String -> IO a
140     readLn,                    -- :: Read a => IO a
141
142     -- * Binary input and output
143
144 #if !defined(__NHC__)
145     openBinaryFile,            -- :: FilePath -> IOMode -> IO Handle
146 #endif
147
148 #if !defined(__HUGS__) && !defined(__NHC__)
149     hSetBinaryMode,            -- :: Handle -> Bool -> IO ()
150     hPutBuf,                   -- :: Handle -> Ptr a -> Int -> IO ()
151     hGetBuf,                   -- :: Handle -> Ptr a -> Int -> IO Int
152     hPutBufNonBlocking,        -- :: Handle -> Ptr a -> Int -> IO Int
153     hGetBufNonBlocking,        -- :: Handle -> Ptr a -> Int -> IO Int
154 #endif
155
156     module System.IO.Error,
157   ) where
158
159 #ifdef __GLASGOW_HASKELL__
160 import GHC.Base
161 import GHC.IOBase       -- Together these four Prelude modules define
162 import GHC.Handle       -- all the stuff exported by IO for the GHC version
163 import GHC.IO
164 import GHC.ST           ( fixST )
165 import GHC.Exception
166 import GHC.Num
167 import GHC.Read
168 import GHC.Show
169 #endif
170
171 #ifdef __HUGS__
172 import Hugs.IO
173 import Hugs.IOExts
174 #endif
175
176 #ifdef __NHC__
177 import IO
178   ( Handle ()
179   , HandlePosn ()
180   , IOMode (ReadMode,WriteMode,AppendMode,ReadWriteMode)
181   , BufferMode (NoBuffering,LineBuffering,BlockBuffering)
182   , SeekMode (AbsoluteSeek,RelativeSeek,SeekFromEnd)
183   , stdin, stdout, stderr
184   , openFile                  -- :: FilePath -> IOMode -> IO Handle
185   , hClose                    -- :: Handle -> IO ()
186   , hFileSize                 -- :: Handle -> IO Integer
187   , hIsEOF                    -- :: Handle -> IO Bool
188   , isEOF                     -- :: IO Bool
189   , hSetBuffering             -- :: Handle -> BufferMode -> IO ()
190   , hGetBuffering             -- :: Handle -> IO BufferMode
191   , hFlush                    -- :: Handle -> IO ()
192   , hGetPosn                  -- :: Handle -> IO HandlePosn
193   , hSetPosn                  -- :: HandlePosn -> IO ()
194   , hSeek                     -- :: Handle -> SeekMode -> Integer -> IO ()
195   , hWaitForInput             -- :: Handle -> Int -> IO Bool
196   , hGetChar                  -- :: Handle -> IO Char
197   , hGetLine                  -- :: Handle -> IO [Char]
198   , hLookAhead                -- :: Handle -> IO Char
199   , hGetContents              -- :: Handle -> IO [Char]
200   , hPutChar                  -- :: Handle -> Char -> IO ()
201   , hPutStr                   -- :: Handle -> [Char] -> IO ()
202   , hIsOpen, hIsClosed        -- :: Handle -> IO Bool
203   , hIsReadable, hIsWritable  -- :: Handle -> IO Bool
204   , hIsSeekable               -- :: Handle -> IO Bool
205
206   , IO ()
207   , FilePath                  -- :: String
208   )
209 import NHC.IOExtras (fixIO)
210 #endif
211
212 import System.IO.Error (
213     isAlreadyExistsError, isDoesNotExistError,  -- :: IOError -> Bool
214     isAlreadyInUseError, isFullError, 
215     isEOFError, isIllegalOperation, 
216     isPermissionError, isUserError, 
217  
218     ioeGetErrorString,         -- :: IOError -> String
219     ioeGetHandle,              -- :: IOError -> Maybe Handle
220     ioeGetFileName,            -- :: IOError -> Maybe FilePath
221  
222     try,                       -- :: IO a -> IO (Either IOError a)
223  
224     -- re-exports of Prelude names
225     IOError,
226     ioError,                   -- :: IOError -> IO a
227     userError,                 -- :: String  -> IOError
228     catch                      -- :: IO a    -> (IOError -> IO a) -> IO a
229   )
230
231 -- -----------------------------------------------------------------------------
232 -- Standard IO
233
234 #ifndef __HUGS__
235 -- | Write a character to the standard output device
236 -- (same as 'hPutChar' 'stdout').
237
238 putChar         :: Char -> IO ()
239 putChar c       =  hPutChar stdout c
240
241 -- | Write a string to the standard output device
242 -- (same as 'hPutStr' 'stdout').
243
244 putStr          :: String -> IO ()
245 putStr s        =  hPutStr stdout s
246
247 -- | The same as 'putStrLn', but adds a newline character.
248
249 putStrLn        :: String -> IO ()
250 putStrLn s      =  do putStr s
251                       putChar '\n'
252
253 -- | The 'print' function outputs a value of any printable type to the
254 -- standard output device.
255 -- Printable types are those that are instances of class 'Show'; 'print'
256 -- converts values to strings for output using the 'show' operation and
257 -- adds a newline.
258 --
259 -- For example, a program to print the first 20 integers and their
260 -- powers of 2 could be written as:
261 --
262 -- > main = print ([(n, 2^n) | n <- [0..19]])
263
264 print           :: Show a => a -> IO ()
265 print x         =  putStrLn (show x)
266
267 -- | Read a character from the standard input device
268 -- (same as 'hGetChar' 'stdin').
269
270 getChar         :: IO Char
271 getChar         =  hGetChar stdin
272
273 -- | Read a line from the standard input device
274 -- (same as 'hGetLine' 'stdin').
275
276 getLine         :: IO String
277 getLine         =  hGetLine stdin
278
279 -- | The 'getContents' operation returns all user input as a single string,
280 -- which is read lazily as it is needed
281 -- (same as 'hGetContents' 'stdin').
282
283 getContents     :: IO String
284 getContents     =  hGetContents stdin
285
286 -- | The 'interact' function takes a function of type @String->String@
287 -- as its argument.  The entire input from the standard input device is
288 -- passed to this function as its argument, and the resulting string is
289 -- output on the standard output device.
290
291 interact        ::  (String -> String) -> IO ()
292 interact f      =   do s <- getContents
293                        putStr (f s)
294
295 -- | The 'readFile' function reads a file and
296 -- returns the contents of the file as a string.
297 -- The file is read lazily, on demand, as with 'getContents'.
298
299 readFile        :: FilePath -> IO String
300 readFile name   =  openFile name ReadMode >>= hGetContents
301
302 -- | The computation 'writeFile' @file str@ function writes the string @str@,
303 -- to the file @file@.
304
305 writeFile       :: FilePath -> String -> IO ()
306 writeFile name str = do
307     hdl <- openFile name WriteMode
308     hPutStr hdl str
309     hClose hdl
310
311 -- | The computation 'appendFile' @file str@ function appends the string @str@,
312 -- to the file @file@.
313 --
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.
317 --
318 -- > main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
319
320 appendFile      :: FilePath -> String -> IO ()
321 appendFile name str = do
322     hdl <- openFile name AppendMode
323     hPutStr hdl str
324     hClose hdl
325
326 -- | The 'readLn' function combines 'getLine' and 'readIO'.
327
328 readLn          :: Read a => IO a
329 readLn          =  do l <- getLine
330                       r <- readIO l
331                       return r
332
333 -- | The 'readIO' function is similar to 'read' except that it signals
334 -- parse failure to the 'IO' monad instead of terminating the program.
335
336 readIO          :: Read a => String -> IO a
337 readIO s        =  case (do { (x,t) <- reads s ;
338                               ("","") <- lex t ;
339                               return x }) of
340                         [x]    -> return x
341                         []     -> ioError (userError "Prelude.readIO: no parse")
342                         _      -> ioError (userError "Prelude.readIO: ambiguous parse")
343 #endif  /* __HUGS__ */
344
345 -- | Computation 'hReady' @hdl@ indicates whether at least one item is
346 -- available for input from handle @hdl@.
347 -- 
348 -- This operation may fail with:
349 --
350 --  * 'isEOFError' if the end of file has been reached.
351
352 hReady          :: Handle -> IO Bool
353 hReady h        =  hWaitForInput h 0
354
355 -- | The same as 'hPutStr', but adds a newline character.
356
357 hPutStrLn       :: Handle -> String -> IO ()
358 hPutStrLn hndl str = do
359  hPutStr  hndl str
360  hPutChar hndl '\n'
361
362 -- | Computation 'hPrint' @hdl t@ writes the string representation of @t@
363 -- given by the 'shows' function to the file or channel managed by @hdl@
364 -- and appends a newline.
365 --
366 -- This operation may fail with:
367 --
368 --  * 'isFullError' if the device is full; or
369 --
370 --  * 'isPermissionError' if another system resource limit would be exceeded.
371
372 hPrint          :: Show a => Handle -> a -> IO ()
373 hPrint hdl      =  hPutStrLn hdl . show
374
375 -- ---------------------------------------------------------------------------
376 -- fixIO
377
378 #ifdef __GLASGOW_HASKELL__
379 fixIO           :: (a -> IO a) -> IO a
380 fixIO m         = stToIO (fixST (ioToST . m))
381 #endif
382
383 -- $locking
384 -- Implementations should enforce as far as possible, at least locally to the
385 -- Haskell process, multiple-reader single-writer locking on files.
386 -- That is, /there may either be many handles on the same file which manage
387 -- input, or just one handle on the file which manages output/.  If any
388 -- open or semi-closed handle is managing a file for output, no new
389 -- handle can be allocated for that file.  If any open or semi-closed
390 -- handle is managing a file for input, new handles can only be allocated
391 -- if they do not manage output.  Whether two files are the same is
392 -- implementation-dependent, but they should normally be the same if they
393 -- have the same absolute path name and neither has been renamed, for
394 -- example.
395 --
396 -- /Warning/: the 'readFile' operation holds a semi-closed handle on
397 -- the file until the entire contents of the file have been consumed.
398 -- It follows that an attempt to write to a file (using 'writeFile', for
399 -- example) that was earlier opened by 'readFile' will usually result in
400 -- failure with 'isAlreadyInUseError'.