use bracket in appendFile (like writeFile)
[ghc-base.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     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 writeFile :: FilePath -> String -> IO ()
298 writeFile f txt = bracket (openFile f WriteMode) hClose
299                           (\hdl -> hPutStr hdl txt) 
300
301 -- | The computation 'appendFile' @file str@ function appends the string @str@,
302 -- to the file @file@.
303 --
304 -- Note that 'writeFile' and 'appendFile' write a literal string
305 -- to a file.  To write a value of any printable type, as with 'print',
306 -- use the 'show' function to convert the value to a string first.
307 --
308 -- > main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
309
310 appendFile      :: FilePath -> String -> IO ()
311 appendFile f txt = bracket (openFile f AppendMode) hClose
312                            (\hdl -> hPutStr hdl txt)
313
314 -- | The 'readLn' function combines 'getLine' and 'readIO'.
315
316 readLn          :: Read a => IO a
317 readLn          =  do l <- getLine
318                       r <- readIO l
319                       return r
320
321 -- | The 'readIO' function is similar to 'read' except that it signals
322 -- parse failure to the 'IO' monad instead of terminating the program.
323
324 readIO          :: Read a => String -> IO a
325 readIO s        =  case (do { (x,t) <- reads s ;
326                               ("","") <- lex t ;
327                               return x }) of
328                         [x]    -> return x
329                         []     -> ioError (userError "Prelude.readIO: no parse")
330                         _      -> ioError (userError "Prelude.readIO: ambiguous parse")
331 #endif  /* __GLASGOW_HASKELL__ */
332
333 #ifndef __NHC__
334 -- | Computation 'hReady' @hdl@ indicates whether at least one item is
335 -- available for input from handle @hdl@.
336 -- 
337 -- This operation may fail with:
338 --
339 --  * 'System.IO.Error.isEOFError' if the end of file has been reached.
340
341 hReady          :: Handle -> IO Bool
342 hReady h        =  hWaitForInput h 0
343
344 -- | The same as 'hPutStr', but adds a newline character.
345
346 hPutStrLn       :: Handle -> String -> IO ()
347 hPutStrLn hndl str = do
348  hPutStr  hndl str
349  hPutChar hndl '\n'
350
351 -- | Computation 'hPrint' @hdl t@ writes the string representation of @t@
352 -- given by the 'shows' function to the file or channel managed by @hdl@
353 -- and appends a newline.
354 --
355 -- This operation may fail with:
356 --
357 --  * 'System.IO.Error.isFullError' if the device is full; or
358 --
359 --  * 'System.IO.Error.isPermissionError' if another system resource limit would be exceeded.
360
361 hPrint          :: Show a => Handle -> a -> IO ()
362 hPrint hdl      =  hPutStrLn hdl . show
363 #endif /* !__NHC__ */
364
365 -- ---------------------------------------------------------------------------
366 -- fixIO
367
368 #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__)
369 fixIO :: (a -> IO a) -> IO a
370 fixIO k = do
371     ref <- newIORef (throw NonTermination)
372     ans <- unsafeInterleaveIO (readIORef ref)
373     result <- k ans
374     writeIORef ref result
375     return result
376
377 -- NOTE: we do our own explicit black holing here, because GHC's lazy
378 -- blackholing isn't enough.  In an infinite loop, GHC may run the IO
379 -- computation a few times before it notices the loop, which is wrong.
380 #endif
381
382 #if defined(__NHC__)
383 -- Assume a unix platform, where text and binary I/O are identical.
384 openBinaryFile = openFile
385 hSetBinaryMode _ _ = return ()
386 #endif
387
388 -- $locking
389 -- Implementations should enforce as far as possible, at least locally to the
390 -- Haskell process, multiple-reader single-writer locking on files.
391 -- That is, /there may either be many handles on the same file which manage
392 -- input, or just one handle on the file which manages output/.  If any
393 -- open or semi-closed handle is managing a file for output, no new
394 -- handle can be allocated for that file.  If any open or semi-closed
395 -- handle is managing a file for input, new handles can only be allocated
396 -- if they do not manage output.  Whether two files are the same is
397 -- implementation-dependent, but they should normally be the same if they
398 -- have the same absolute path name and neither has been renamed, for
399 -- example.
400 --
401 -- /Warning/: the 'readFile' operation holds a semi-closed handle on
402 -- the file until the entire contents of the file have been consumed.
403 -- It follows that an attempt to write to a file (using 'writeFile', for
404 -- example) that was earlier opened by 'readFile' will usually result in
405 -- failure with 'System.IO.Error.isAlreadyInUseError'.
406
407 -- -----------------------------------------------------------------------------
408 -- Utils
409
410 -- Copied here to avoid recursive dependency with Control.Exception
411 bracket 
412         :: IO a         -- ^ computation to run first (\"acquire resource\")
413         -> (a -> IO b)  -- ^ computation to run last (\"release resource\")
414         -> (a -> IO c)  -- ^ computation to run in-between
415         -> IO c         -- returns the value from the in-between computation
416 bracket before after thing =
417   block (do
418     a <- before 
419     r <- catchException
420            (unblock (thing a))
421            (\e -> do { after a; throw e })
422     after a
423     return r
424  )