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