[project @ 2003-08-04 10:05:32 by ross]
[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 #endif
153
154     module System.IO.Error,
155   ) where
156
157 #ifdef __GLASGOW_HASKELL__
158 import GHC.Base
159 import GHC.IOBase       -- Together these four Prelude modules define
160 import GHC.Handle       -- all the stuff exported by IO for the GHC version
161 import GHC.IO
162 import GHC.ST           ( fixST )
163 import GHC.Exception
164 import GHC.Num
165 import GHC.Read
166 import GHC.Show
167 #endif
168
169 #ifdef __HUGS__
170 import Hugs.IO
171 import Hugs.IOExts
172 #endif
173
174 #ifdef __NHC__
175 import IO
176   ( Handle ()
177   , HandlePosn ()
178   , IOMode (ReadMode,WriteMode,AppendMode,ReadWriteMode)
179   , BufferMode (NoBuffering,LineBuffering,BlockBuffering)
180   , SeekMode (AbsoluteSeek,RelativeSeek,SeekFromEnd)
181   , stdin, stdout, stderr
182   , openFile                  -- :: FilePath -> IOMode -> IO Handle
183   , hClose                    -- :: Handle -> IO ()
184   , hFileSize                 -- :: Handle -> IO Integer
185   , hIsEOF                    -- :: Handle -> IO Bool
186   , isEOF                     -- :: IO Bool
187   , hSetBuffering             -- :: Handle -> BufferMode -> IO ()
188   , hGetBuffering             -- :: Handle -> IO BufferMode
189   , hFlush                    -- :: Handle -> IO ()
190   , hGetPosn                  -- :: Handle -> IO HandlePosn
191   , hSetPosn                  -- :: HandlePosn -> IO ()
192   , hSeek                     -- :: Handle -> SeekMode -> Integer -> IO ()
193   , hWaitForInput             -- :: Handle -> Int -> IO Bool
194   , hGetChar                  -- :: Handle -> IO Char
195   , hGetLine                  -- :: Handle -> IO [Char]
196   , hLookAhead                -- :: Handle -> IO Char
197   , hGetContents              -- :: Handle -> IO [Char]
198   , hPutChar                  -- :: Handle -> Char -> IO ()
199   , hPutStr                   -- :: Handle -> [Char] -> IO ()
200   , hIsOpen, hIsClosed        -- :: Handle -> IO Bool
201   , hIsReadable, hIsWritable  -- :: Handle -> IO Bool
202   , hIsSeekable               -- :: Handle -> IO Bool
203
204   , IO ()
205   , FilePath                  -- :: String
206   )
207 import NHC.Internal (unsafePerformIO)
208 #endif
209
210 import System.IO.Error (
211     isAlreadyExistsError, isDoesNotExistError,  -- :: IOError -> Bool
212     isAlreadyInUseError, isFullError, 
213     isEOFError, isIllegalOperation, 
214     isPermissionError, isUserError, 
215  
216     ioeGetErrorString,         -- :: IOError -> String
217     ioeGetHandle,              -- :: IOError -> Maybe Handle
218     ioeGetFileName,            -- :: IOError -> Maybe FilePath
219  
220     try,                       -- :: IO a -> IO (Either IOError a)
221  
222     -- re-exports of Prelude names
223     IOError,
224     ioError,                   -- :: IOError -> IO a
225     userError,                 -- :: String  -> IOError
226     catch                      -- :: IO a    -> (IOError -> IO a) -> IO a
227   )
228
229 -- -----------------------------------------------------------------------------
230 -- Standard IO
231
232 #ifndef __HUGS__
233 -- | Write a character to the standard output device
234 -- (same as 'hPutChar' 'stdout').
235
236 putChar         :: Char -> IO ()
237 putChar c       =  hPutChar stdout c
238
239 -- | Write a string to the standard output device
240 -- (same as 'hPutStr' 'stdout').
241
242 putStr          :: String -> IO ()
243 putStr s        =  hPutStr stdout s
244
245 -- | The same as 'putStrLn', but adds a newline character.
246
247 putStrLn        :: String -> IO ()
248 putStrLn s      =  do putStr s
249                       putChar '\n'
250
251 -- | The 'print' function outputs a value of any printable type to the
252 -- standard output device.
253 -- Printable types are those that are instances of class 'Show'; 'print'
254 -- converts values to strings for output using the 'show' operation and
255 -- adds a newline.
256 --
257 -- For example, a program to print the first 20 integers and their
258 -- powers of 2 could be written as:
259 --
260 -- > main = print ([(n, 2^n) | n <- [0..19]])
261
262 print           :: Show a => a -> IO ()
263 print x         =  putStrLn (show x)
264
265 -- | Read a character from the standard input device
266 -- (same as 'hGetChar' 'stdin').
267
268 getChar         :: IO Char
269 getChar         =  hGetChar stdin
270
271 -- | Read a line from the standard input device
272 -- (same as 'hGetLine' 'stdin').
273
274 getLine         :: IO String
275 getLine         =  hGetLine stdin
276
277 -- | The 'getContents' operation returns all user input as a single string,
278 -- which is read lazily as it is needed
279 -- (same as 'hGetContents' 'stdin').
280
281 getContents     :: IO String
282 getContents     =  hGetContents stdin
283
284 -- | The 'interact' function takes a function of type @String->String@
285 -- as its argument.  The entire input from the standard input device is
286 -- passed to this function as its argument, and the resulting string is
287 -- output on the standard output device.
288
289 interact        ::  (String -> String) -> IO ()
290 interact f      =   do s <- getContents
291                        putStr (f s)
292
293 -- | The 'readFile' function reads a file and
294 -- returns the contents of the file as a string.
295 -- The file is read lazily, on demand, as with 'getContents'.
296
297 readFile        :: FilePath -> IO String
298 readFile name   =  openFile name ReadMode >>= hGetContents
299
300 -- | The computation 'writeFile' @file str@ function writes the string @str@,
301 -- to the file @file@.
302
303 writeFile       :: FilePath -> String -> IO ()
304 writeFile name str = do
305     hdl <- openFile name WriteMode
306     hPutStr hdl str
307     hClose hdl
308
309 -- | The computation 'appendFile' @file str@ function appends the string @str@,
310 -- to the file @file@.
311 --
312 -- Note that 'writeFile' and 'appendFile' write a literal string
313 -- to a file.  To write a value of any printable type, as with 'print',
314 -- use the 'show' function to convert the value to a string first.
315 --
316 -- > main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
317
318 appendFile      :: FilePath -> String -> IO ()
319 appendFile name str = do
320     hdl <- openFile name AppendMode
321     hPutStr hdl str
322     hClose hdl
323
324 -- | The 'readLn' function combines 'getLine' and 'readIO'.
325
326 readLn          :: Read a => IO a
327 readLn          =  do l <- getLine
328                       r <- readIO l
329                       return r
330
331 -- | The 'readIO' function is similar to 'read' except that it signals
332 -- parse failure to the 'IO' monad instead of terminating the program.
333
334 readIO          :: Read a => String -> IO a
335 readIO s        =  case (do { (x,t) <- reads s ;
336                               ("","") <- lex t ;
337                               return x }) of
338                         [x]    -> return x
339                         []     -> ioError (userError "Prelude.readIO: no parse")
340                         _      -> ioError (userError "Prelude.readIO: ambiguous parse")
341 #endif  /* __HUGS__ */
342
343 -- | Computation 'hReady' @hdl@ indicates whether at least one item is
344 -- available for input from handle "hdl".
345 -- 
346 -- This operation may fail with:
347 --
348 --  * 'isEOFError' if the end of file has been reached.
349
350 hReady          :: Handle -> IO Bool
351 hReady h        =  hWaitForInput h 0
352
353 -- | The same as 'hPutStr', but adds a newline character.
354
355 hPutStrLn       :: Handle -> String -> IO ()
356 hPutStrLn hndl str = do
357  hPutStr  hndl str
358  hPutChar hndl '\n'
359
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.
363 --
364 -- This operation may fail with:
365 --
366 --  * 'isFullError' if the device is full; or
367 --
368 --  * 'isPermissionError' if another system resource limit would be exceeded.
369
370 hPrint          :: Show a => Handle -> a -> IO ()
371 hPrint hdl      =  hPutStrLn hdl . show
372
373 -- ---------------------------------------------------------------------------
374 -- fixIO
375
376 #ifdef __GLASGOW_HASKELL__
377 fixIO           :: (a -> IO a) -> IO a
378 fixIO m         = stToIO (fixST (ioToST . m))
379 #endif
380 #ifdef __NHC__
381 fixIO           :: (a -> IO a) -> IO a
382 fixIO f         = let x = unsafePerformIO (f x) in return x
383 #endif
384
385 -- $locking
386 -- Implementations should enforce as far as possible, at least locally to the
387 -- Haskell process, multiple-reader single-writer locking on files.
388 -- That is, /there may either be many handles on the same file which manage
389 -- input, or just one handle on the file which manages output/.  If any
390 -- open or semi-closed handle is managing a file for output, no new
391 -- handle can be allocated for that file.  If any open or semi-closed
392 -- handle is managing a file for input, new handles can only be allocated
393 -- if they do not manage output.  Whether two files are the same is
394 -- implementation-dependent, but they should normally be the same if they
395 -- have the same absolute path name and neither has been renamed, for
396 -- example.
397 --
398 -- /Warning/: the 'readFile' operation holds a semi-closed handle on
399 -- the file until the entire contents of the file have been consumed.
400 -- It follows that an attempt to write to a file (using 'writeFile', for
401 -- example) that was earlier opened by 'readFile' will usually result in
402 -- failure with 'isAlreadyInUseError'.