74682509e72302b9f3c81f3dc99ed6a6f0c89e87
[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   :  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 and changing the size of a file
61
62     hFileSize,                 -- :: Handle -> IO Integer
63 #ifdef __GLASGOW_HASKELL__
64     hSetFileSize,              -- :: Handle -> Integer -> IO ()
65 #endif
66
67     -- ** Detecting the end of input
68
69     hIsEOF,                    -- :: Handle -> IO Bool
70     isEOF,                     -- :: IO Bool
71
72     -- ** Buffering operations
73
74     BufferMode(NoBuffering,LineBuffering,BlockBuffering),
75     hSetBuffering,             -- :: Handle -> BufferMode -> IO ()
76     hGetBuffering,             -- :: Handle -> IO BufferMode
77     hFlush,                    -- :: Handle -> IO ()
78
79     -- ** Repositioning handles
80
81     hGetPosn,                  -- :: Handle -> IO HandlePosn
82     hSetPosn,                  -- :: HandlePosn -> IO ()
83     HandlePosn,                -- abstract, instance of: Eq, Show.
84
85     hSeek,                     -- :: Handle -> SeekMode -> Integer -> IO ()
86     SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),
87 #if !defined(__NHC__)
88     hTell,                     -- :: Handle -> IO Integer
89 #endif
90
91     -- ** Handle properties
92
93     hIsOpen, hIsClosed,        -- :: Handle -> IO Bool
94     hIsReadable, hIsWritable,  -- :: Handle -> IO Bool
95     hIsSeekable,               -- :: Handle -> IO Bool
96
97     -- ** Terminal operations
98
99 #if !defined(__NHC__)
100     hIsTerminalDevice,          -- :: Handle -> IO Bool
101
102     hSetEcho,                   -- :: Handle -> Bool -> IO ()
103     hGetEcho,                   -- :: Handle -> IO Bool
104 #endif
105
106     -- ** Showing handle state
107
108 #ifdef __GLASGOW_HASKELL__
109     hShow,                      -- :: Handle -> IO String
110 #endif
111
112     -- * Text input and output
113
114     -- ** Text input
115
116     hWaitForInput,             -- :: Handle -> Int -> IO Bool
117     hReady,                    -- :: Handle -> IO Bool
118     hGetChar,                  -- :: Handle -> IO Char
119     hGetLine,                  -- :: Handle -> IO [Char]
120     hLookAhead,                -- :: Handle -> IO Char
121     hGetContents,              -- :: Handle -> IO [Char]
122
123     -- ** Text output
124
125     hPutChar,                  -- :: Handle -> Char -> IO ()
126     hPutStr,                   -- :: Handle -> [Char] -> IO ()
127     hPutStrLn,                 -- :: Handle -> [Char] -> IO ()
128     hPrint,                    -- :: Show a => Handle -> a -> IO ()
129
130     -- ** Special cases for standard input and output
131
132     -- | These functions are also exported by the "Prelude".
133
134     interact,                  -- :: (String -> String) -> IO ()
135     putChar,                   -- :: Char   -> IO ()
136     putStr,                    -- :: String -> IO () 
137     putStrLn,                  -- :: String -> IO ()
138     print,                     -- :: Show a => a -> IO ()
139     getChar,                   -- :: IO Char
140     getLine,                   -- :: IO String
141     getContents,               -- :: IO String
142     readIO,                    -- :: Read a => String -> IO a
143     readLn,                    -- :: Read a => IO a
144
145     -- * Binary input and output
146
147     openBinaryFile,            -- :: FilePath -> IOMode -> IO Handle
148     hSetBinaryMode,            -- :: Handle -> Bool -> IO ()
149 #if !defined(__NHC__)
150     hPutBuf,                   -- :: Handle -> Ptr a -> Int -> IO ()
151     hGetBuf,                   -- :: Handle -> Ptr a -> Int -> IO Int
152 #endif
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
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 System.IO.Unsafe ( unsafeInterleaveIO )
183 #endif
184
185 #ifdef __NHC__
186 import IO
187   ( Handle ()
188   , HandlePosn ()
189   , IOMode (ReadMode,WriteMode,AppendMode,ReadWriteMode)
190   , BufferMode (NoBuffering,LineBuffering,BlockBuffering)
191   , SeekMode (AbsoluteSeek,RelativeSeek,SeekFromEnd)
192   , stdin, stdout, stderr
193   , openFile                  -- :: FilePath -> IOMode -> IO Handle
194   , hClose                    -- :: Handle -> IO ()
195   , hFileSize                 -- :: Handle -> IO Integer
196   , hIsEOF                    -- :: Handle -> IO Bool
197   , isEOF                     -- :: IO Bool
198   , hSetBuffering             -- :: Handle -> BufferMode -> IO ()
199   , hGetBuffering             -- :: Handle -> IO BufferMode
200   , hFlush                    -- :: Handle -> IO ()
201   , hGetPosn                  -- :: Handle -> IO HandlePosn
202   , hSetPosn                  -- :: HandlePosn -> IO ()
203   , hSeek                     -- :: Handle -> SeekMode -> Integer -> IO ()
204   , hWaitForInput             -- :: Handle -> Int -> IO Bool
205   , hGetChar                  -- :: Handle -> IO Char
206   , hGetLine                  -- :: Handle -> IO [Char]
207   , hLookAhead                -- :: Handle -> IO Char
208   , hGetContents              -- :: Handle -> IO [Char]
209   , hPutChar                  -- :: Handle -> Char -> IO ()
210   , hPutStr                   -- :: Handle -> [Char] -> IO ()
211   , hPutStrLn                 -- :: Handle -> [Char] -> IO ()
212   , hPrint                    -- :: Handle -> [Char] -> IO ()
213   , hReady                    -- :: Handle -> [Char] -> IO ()
214   , hIsOpen, hIsClosed        -- :: Handle -> IO Bool
215   , hIsReadable, hIsWritable  -- :: Handle -> IO Bool
216   , hIsSeekable               -- :: Handle -> IO Bool
217
218   , IO ()
219   , FilePath                  -- :: String
220   )
221 import NHC.IOExtras (fixIO)
222 #endif
223
224 -- -----------------------------------------------------------------------------
225 -- Standard IO
226
227 #ifdef __GLASGOW_HASKELL__
228 -- | Write a character to the standard output device
229 -- (same as 'hPutChar' 'stdout').
230
231 putChar         :: Char -> IO ()
232 putChar c       =  hPutChar stdout c
233
234 -- | Write a string to the standard output device
235 -- (same as 'hPutStr' 'stdout').
236
237 putStr          :: String -> IO ()
238 putStr s        =  hPutStr stdout s
239
240 -- | The same as 'putStr', but adds a newline character.
241
242 putStrLn        :: String -> IO ()
243 putStrLn s      =  do putStr s
244                       putChar '\n'
245
246 -- | The 'print' function outputs a value of any printable type to the
247 -- standard output device.
248 -- Printable types are those that are instances of class 'Show'; 'print'
249 -- converts values to strings for output using the 'show' operation and
250 -- adds a newline.
251 --
252 -- For example, a program to print the first 20 integers and their
253 -- powers of 2 could be written as:
254 --
255 -- > main = print ([(n, 2^n) | n <- [0..19]])
256
257 print           :: Show a => a -> IO ()
258 print x         =  putStrLn (show x)
259
260 -- | Read a character from the standard input device
261 -- (same as 'hGetChar' 'stdin').
262
263 getChar         :: IO Char
264 getChar         =  hGetChar stdin
265
266 -- | Read a line from the standard input device
267 -- (same as 'hGetLine' 'stdin').
268
269 getLine         :: IO String
270 getLine         =  hGetLine stdin
271
272 -- | The 'getContents' operation returns all user input as a single string,
273 -- which is read lazily as it is needed
274 -- (same as 'hGetContents' 'stdin').
275
276 getContents     :: IO String
277 getContents     =  hGetContents stdin
278
279 -- | The 'interact' function takes a function of type @String->String@
280 -- as its argument.  The entire input from the standard input device is
281 -- passed to this function as its argument, and the resulting string is
282 -- output on the standard output device.
283
284 interact        ::  (String -> String) -> IO ()
285 interact f      =   do s <- getContents
286                        putStr (f s)
287
288 -- | The 'readFile' function reads a file and
289 -- returns the contents of the file as a string.
290 -- The file is read lazily, on demand, as with 'getContents'.
291
292 readFile        :: FilePath -> IO String
293 readFile name   =  openFile name ReadMode >>= hGetContents
294
295 -- | The computation 'writeFile' @file str@ function writes the string @str@,
296 -- to the file @file@.
297
298 writeFile       :: FilePath -> String -> IO ()
299 writeFile name str = do
300     hdl <- openFile name WriteMode
301     hPutStr hdl str
302     hClose hdl
303
304 -- | The computation 'appendFile' @file str@ function appends the string @str@,
305 -- to the file @file@.
306 --
307 -- Note that 'writeFile' and 'appendFile' write a literal string
308 -- to a file.  To write a value of any printable type, as with 'print',
309 -- use the 'show' function to convert the value to a string first.
310 --
311 -- > main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
312
313 appendFile      :: FilePath -> String -> IO ()
314 appendFile name str = do
315     hdl <- openFile name AppendMode
316     hPutStr hdl str
317     hClose hdl
318
319 -- | The 'readLn' function combines 'getLine' and 'readIO'.
320
321 readLn          :: Read a => IO a
322 readLn          =  do l <- getLine
323                       r <- readIO l
324                       return r
325
326 -- | The 'readIO' function is similar to 'read' except that it signals
327 -- parse failure to the 'IO' monad instead of terminating the program.
328
329 readIO          :: Read a => String -> IO a
330 readIO s        =  case (do { (x,t) <- reads s ;
331                               ("","") <- lex t ;
332                               return x }) of
333                         [x]    -> return x
334                         []     -> ioError (userError "Prelude.readIO: no parse")
335                         _      -> ioError (userError "Prelude.readIO: ambiguous parse")
336 #endif  /* __GLASGOW_HASKELL__ */
337
338 #ifndef __NHC__
339 -- | Computation 'hReady' @hdl@ indicates whether at least one item is
340 -- available for input from handle @hdl@.
341 -- 
342 -- This operation may fail with:
343 --
344 --  * 'isEOFError' if the end of file has been reached.
345
346 hReady          :: Handle -> IO Bool
347 hReady h        =  hWaitForInput h 0
348
349 -- | The same as 'hPutStr', but adds a newline character.
350
351 hPutStrLn       :: Handle -> String -> IO ()
352 hPutStrLn hndl str = do
353  hPutStr  hndl str
354  hPutChar hndl '\n'
355
356 -- | Computation 'hPrint' @hdl t@ writes the string representation of @t@
357 -- given by the 'shows' function to the file or channel managed by @hdl@
358 -- and appends a newline.
359 --
360 -- This operation may fail with:
361 --
362 --  * 'isFullError' if the device is full; or
363 --
364 --  * 'isPermissionError' if another system resource limit would be exceeded.
365
366 hPrint          :: Show a => Handle -> a -> IO ()
367 hPrint hdl      =  hPutStrLn hdl . show
368 #endif /* !__NHC__ */
369
370 -- ---------------------------------------------------------------------------
371 -- fixIO
372
373 #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__)
374 fixIO :: (a -> IO a) -> IO a
375 fixIO k = do
376     ref <- newIORef (throw NonTermination)
377     ans <- unsafeInterleaveIO (readIORef ref)
378     result <- k ans
379     writeIORef ref result
380     return result
381
382 -- NOTE: we do our own explicit black holing here, because GHC's lazy
383 -- blackholing isn't enough.  In an infinite loop, GHC may run the IO
384 -- computation a few times before it notices the loop, which is wrong.
385 #endif
386
387 #if defined(__NHC__)
388 -- Assume a unix platform, where text and binary I/O are identical.
389 openBinaryFile = openFile
390 hSetBinaryMode _ _ = return ()
391 #endif
392
393 -- $locking
394 -- Implementations should enforce as far as possible, at least locally to the
395 -- Haskell process, multiple-reader single-writer locking on files.
396 -- That is, /there may either be many handles on the same file which manage
397 -- input, or just one handle on the file which manages output/.  If any
398 -- open or semi-closed handle is managing a file for output, no new
399 -- handle can be allocated for that file.  If any open or semi-closed
400 -- handle is managing a file for input, new handles can only be allocated
401 -- if they do not manage output.  Whether two files are the same is
402 -- implementation-dependent, but they should normally be the same if they
403 -- have the same absolute path name and neither has been renamed, for
404 -- example.
405 --
406 -- /Warning/: the 'readFile' operation holds a semi-closed handle on
407 -- the file until the entire contents of the file have been consumed.
408 -- It follows that an attempt to write to a file (using 'writeFile', for
409 -- example) that was earlier opened by 'readFile' will usually result in
410 -- failure with 'isAlreadyInUseError'.