Tweak temporary file filename chooser
[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     withFile,
40     openFile,                  -- :: FilePath -> IOMode -> IO Handle
41     IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),
42
43     -- ** Closing files
44
45     hClose,                    -- :: Handle -> IO ()
46
47     -- ** Special cases
48
49     -- | These functions are also exported by the "Prelude".
50
51     readFile,                  -- :: FilePath -> IO String
52     writeFile,                 -- :: FilePath -> String -> IO ()
53     appendFile,                -- :: FilePath -> String -> IO ()
54
55     -- ** File locking
56
57     -- $locking
58
59     -- * Operations on handles
60
61     -- ** Determining and changing the size of a file
62
63     hFileSize,                 -- :: Handle -> IO Integer
64 #ifdef __GLASGOW_HASKELL__
65     hSetFileSize,              -- :: Handle -> Integer -> IO ()
66 #endif
67
68     -- ** Detecting the end of input
69
70     hIsEOF,                    -- :: Handle -> IO Bool
71     isEOF,                     -- :: IO Bool
72
73     -- ** Buffering operations
74
75     BufferMode(NoBuffering,LineBuffering,BlockBuffering),
76     hSetBuffering,             -- :: Handle -> BufferMode -> IO ()
77     hGetBuffering,             -- :: Handle -> IO BufferMode
78     hFlush,                    -- :: Handle -> IO ()
79
80     -- ** Repositioning handles
81
82     hGetPosn,                  -- :: Handle -> IO HandlePosn
83     hSetPosn,                  -- :: HandlePosn -> IO ()
84     HandlePosn,                -- abstract, instance of: Eq, Show.
85
86     hSeek,                     -- :: Handle -> SeekMode -> Integer -> IO ()
87     SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),
88 #if !defined(__NHC__)
89     hTell,                     -- :: Handle -> IO Integer
90 #endif
91
92     -- ** Handle properties
93
94     hIsOpen, hIsClosed,        -- :: Handle -> IO Bool
95     hIsReadable, hIsWritable,  -- :: Handle -> IO Bool
96     hIsSeekable,               -- :: Handle -> IO Bool
97
98     -- ** Terminal operations
99
100 #if !defined(__NHC__)
101     hIsTerminalDevice,          -- :: Handle -> IO Bool
102
103     hSetEcho,                   -- :: Handle -> Bool -> IO ()
104     hGetEcho,                   -- :: Handle -> IO Bool
105 #endif
106
107     -- ** Showing handle state
108
109 #ifdef __GLASGOW_HASKELL__
110     hShow,                      -- :: Handle -> IO String
111 #endif
112
113     -- * Text input and output
114
115     -- ** Text input
116
117     hWaitForInput,             -- :: Handle -> Int -> IO Bool
118     hReady,                    -- :: Handle -> IO Bool
119     hGetChar,                  -- :: Handle -> IO Char
120     hGetLine,                  -- :: Handle -> IO [Char]
121     hLookAhead,                -- :: Handle -> IO Char
122     hGetContents,              -- :: Handle -> IO [Char]
123
124     -- ** Text output
125
126     hPutChar,                  -- :: Handle -> Char -> IO ()
127     hPutStr,                   -- :: Handle -> [Char] -> IO ()
128     hPutStrLn,                 -- :: Handle -> [Char] -> IO ()
129     hPrint,                    -- :: Show a => Handle -> a -> IO ()
130
131     -- ** Special cases for standard input and output
132
133     -- | These functions are also exported by the "Prelude".
134
135     interact,                  -- :: (String -> String) -> IO ()
136     putChar,                   -- :: Char   -> IO ()
137     putStr,                    -- :: String -> IO () 
138     putStrLn,                  -- :: String -> IO ()
139     print,                     -- :: Show a => a -> IO ()
140     getChar,                   -- :: IO Char
141     getLine,                   -- :: IO String
142     getContents,               -- :: IO String
143     readIO,                    -- :: Read a => String -> IO a
144     readLn,                    -- :: Read a => IO a
145
146     -- * Binary input and output
147
148     withBinaryFile,
149     openBinaryFile,            -- :: FilePath -> IOMode -> IO Handle
150     hSetBinaryMode,            -- :: Handle -> Bool -> IO ()
151     hPutBuf,                   -- :: Handle -> Ptr a -> Int -> IO ()
152     hGetBuf,                   -- :: Handle -> Ptr a -> Int -> IO Int
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 (not portable: GHC only)
159
160 #ifdef __GLASGOW_HASKELL__
161     openTempFile,
162     openBinaryTempFile,
163 #endif
164   ) where
165
166 import Data.Bits
167 import Data.List
168 import Data.Maybe
169 import Foreign.C.Error
170 import Foreign.C.String
171 import System.Posix.Internals
172
173 #ifdef __GLASGOW_HASKELL__
174 import GHC.Base
175 import GHC.IOBase       -- Together these four Prelude modules define
176 import GHC.Handle       -- all the stuff exported by IO for the GHC version
177 import GHC.IO
178 import GHC.Exception
179 import GHC.Num
180 import GHC.Read
181 import GHC.Show
182 #endif
183
184 #ifdef __HUGS__
185 import Hugs.IO
186 import Hugs.IOExts
187 import Hugs.IORef
188 import Hugs.Prelude     ( throw, Exception(NonTermination) )
189 import Control.Exception ( bracket )
190 import System.IO.Unsafe ( unsafeInterleaveIO )
191 #endif
192
193 #ifdef __NHC__
194 import IO
195   ( Handle ()
196   , HandlePosn ()
197   , IOMode (ReadMode,WriteMode,AppendMode,ReadWriteMode)
198   , BufferMode (NoBuffering,LineBuffering,BlockBuffering)
199   , SeekMode (AbsoluteSeek,RelativeSeek,SeekFromEnd)
200   , stdin, stdout, stderr
201   , openFile                  -- :: FilePath -> IOMode -> IO Handle
202   , hClose                    -- :: Handle -> IO ()
203   , hFileSize                 -- :: Handle -> IO Integer
204   , hIsEOF                    -- :: Handle -> IO Bool
205   , isEOF                     -- :: IO Bool
206   , hSetBuffering             -- :: Handle -> BufferMode -> IO ()
207   , hGetBuffering             -- :: Handle -> IO BufferMode
208   , hFlush                    -- :: Handle -> IO ()
209   , hGetPosn                  -- :: Handle -> IO HandlePosn
210   , hSetPosn                  -- :: HandlePosn -> IO ()
211   , hSeek                     -- :: Handle -> SeekMode -> Integer -> IO ()
212   , hWaitForInput             -- :: Handle -> Int -> IO Bool
213   , hGetChar                  -- :: Handle -> IO Char
214   , hGetLine                  -- :: Handle -> IO [Char]
215   , hLookAhead                -- :: Handle -> IO Char
216   , hGetContents              -- :: Handle -> IO [Char]
217   , hPutChar                  -- :: Handle -> Char -> IO ()
218   , hPutStr                   -- :: Handle -> [Char] -> IO ()
219   , hPutStrLn                 -- :: Handle -> [Char] -> IO ()
220   , hPrint                    -- :: Handle -> [Char] -> IO ()
221   , hReady                    -- :: Handle -> [Char] -> IO ()
222   , hIsOpen, hIsClosed        -- :: Handle -> IO Bool
223   , hIsReadable, hIsWritable  -- :: Handle -> IO Bool
224   , hIsSeekable               -- :: Handle -> IO Bool
225   , bracket
226
227   , IO ()
228   , FilePath                  -- :: String
229   )
230 import NHC.IOExtras (fixIO, hPutBuf, hGetBuf)
231 import NHC.FFI (Ptr)
232 #endif
233
234 -- -----------------------------------------------------------------------------
235 -- Standard IO
236
237 #ifdef __GLASGOW_HASKELL__
238 -- | Write a character to the standard output device
239 -- (same as 'hPutChar' 'stdout').
240
241 putChar         :: Char -> IO ()
242 putChar c       =  hPutChar stdout c
243
244 -- | Write a string to the standard output device
245 -- (same as 'hPutStr' 'stdout').
246
247 putStr          :: String -> IO ()
248 putStr s        =  hPutStr stdout s
249
250 -- | The same as 'putStr', but adds a newline character.
251
252 putStrLn        :: String -> IO ()
253 putStrLn s      =  do putStr s
254                       putChar '\n'
255
256 -- | The 'print' function outputs a value of any printable type to the
257 -- standard output device.
258 -- Printable types are those that are instances of class 'Show'; 'print'
259 -- converts values to strings for output using the 'show' operation and
260 -- adds a newline.
261 --
262 -- For example, a program to print the first 20 integers and their
263 -- powers of 2 could be written as:
264 --
265 -- > main = print ([(n, 2^n) | n <- [0..19]])
266
267 print           :: Show a => a -> IO ()
268 print x         =  putStrLn (show x)
269
270 -- | Read a character from the standard input device
271 -- (same as 'hGetChar' 'stdin').
272
273 getChar         :: IO Char
274 getChar         =  hGetChar stdin
275
276 -- | Read a line from the standard input device
277 -- (same as 'hGetLine' 'stdin').
278
279 getLine         :: IO String
280 getLine         =  hGetLine stdin
281
282 -- | The 'getContents' operation returns all user input as a single string,
283 -- which is read lazily as it is needed
284 -- (same as 'hGetContents' 'stdin').
285
286 getContents     :: IO String
287 getContents     =  hGetContents stdin
288
289 -- | The 'interact' function takes a function of type @String->String@
290 -- as its argument.  The entire input from the standard input device is
291 -- passed to this function as its argument, and the resulting string is
292 -- output on the standard output device.
293
294 interact        ::  (String -> String) -> IO ()
295 interact f      =   do s <- getContents
296                        putStr (f s)
297
298 -- | The 'readFile' function reads a file and
299 -- returns the contents of the file as a string.
300 -- The file is read lazily, on demand, as with 'getContents'.
301
302 readFile        :: FilePath -> IO String
303 readFile name   =  openFile name ReadMode >>= hGetContents
304
305 -- | The computation 'writeFile' @file str@ function writes the string @str@,
306 -- to the file @file@.
307 writeFile :: FilePath -> String -> IO ()
308 writeFile f txt = withFile f WriteMode (\ hdl -> hPutStr hdl txt)
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 f txt = withFile f AppendMode (\ hdl -> hPutStr hdl txt)
321
322 -- | The 'readLn' function combines 'getLine' and 'readIO'.
323
324 readLn          :: Read a => IO a
325 readLn          =  do l <- getLine
326                       r <- readIO l
327                       return r
328
329 -- | The 'readIO' function is similar to 'read' except that it signals
330 -- parse failure to the 'IO' monad instead of terminating the program.
331
332 readIO          :: Read a => String -> IO a
333 readIO s        =  case (do { (x,t) <- reads s ;
334                               ("","") <- lex t ;
335                               return x }) of
336                         [x]    -> return x
337                         []     -> ioError (userError "Prelude.readIO: no parse")
338                         _      -> ioError (userError "Prelude.readIO: ambiguous parse")
339 #endif  /* __GLASGOW_HASKELL__ */
340
341 #ifndef __NHC__
342 -- | Computation 'hReady' @hdl@ indicates whether at least one item is
343 -- available for input from handle @hdl@.
344 -- 
345 -- This operation may fail with:
346 --
347 --  * 'System.IO.Error.isEOFError' if the end of file has been reached.
348
349 hReady          :: Handle -> IO Bool
350 hReady h        =  hWaitForInput h 0
351
352 -- | The same as 'hPutStr', but adds a newline character.
353
354 hPutStrLn       :: Handle -> String -> IO ()
355 hPutStrLn hndl str = do
356  hPutStr  hndl str
357  hPutChar hndl '\n'
358
359 -- | Computation 'hPrint' @hdl t@ writes the string representation of @t@
360 -- given by the 'shows' function to the file or channel managed by @hdl@
361 -- and appends a newline.
362 --
363 -- This operation may fail with:
364 --
365 --  * 'System.IO.Error.isFullError' if the device is full; or
366 --
367 --  * 'System.IO.Error.isPermissionError' if another system resource limit would be exceeded.
368
369 hPrint          :: Show a => Handle -> a -> IO ()
370 hPrint hdl      =  hPutStrLn hdl . show
371 #endif /* !__NHC__ */
372
373 -- | @'withFile' name mode act@ opens a file using 'openFile' and passes
374 -- the resulting handle to the computation @act@.  The handle will be
375 -- closed on exit from 'withFile', whether by normal termination or by
376 -- raising an exception.
377 withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
378 withFile name mode = bracket (openFile name mode) hClose
379
380 -- | @'withBinaryFile' name mode act@ opens a file using 'openBinaryFile'
381 -- and passes the resulting handle to the computation @act@.  The handle
382 -- will be closed on exit from 'withBinaryFile', whether by normal
383 -- termination or by raising an exception.
384 withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
385 withBinaryFile name mode = bracket (openBinaryFile name mode) hClose
386
387 -- ---------------------------------------------------------------------------
388 -- fixIO
389
390 #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__)
391 fixIO :: (a -> IO a) -> IO a
392 fixIO k = do
393     ref <- newIORef (throw NonTermination)
394     ans <- unsafeInterleaveIO (readIORef ref)
395     result <- k ans
396     writeIORef ref result
397     return result
398
399 -- NOTE: we do our own explicit black holing here, because GHC's lazy
400 -- blackholing isn't enough.  In an infinite loop, GHC may run the IO
401 -- computation a few times before it notices the loop, which is wrong.
402 #endif
403
404 #if defined(__NHC__)
405 -- Assume a unix platform, where text and binary I/O are identical.
406 openBinaryFile = openFile
407 hSetBinaryMode _ _ = return ()
408 #endif
409
410 -- | The function creates a temporary file in ReadWrite mode.
411 -- The created file isn\'t deleted automatically, so you need to delete it manually.
412 openTempFile :: FilePath   -- ^ Directory in which to create the file
413              -> String     -- ^ File name template. If the template is \"foo.ext\" then
414                            -- the create file will be \"fooXXX.ext\" where XXX is some
415                            -- random number.
416              -> IO (FilePath, Handle)
417 openTempFile tmp_dir template = openTempFile' "openTempFile" tmp_dir template False
418
419 -- | Like 'openTempFile', but opens the file in binary mode. See 'openBinaryFile' for more comments.
420 openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle)
421 openBinaryTempFile tmp_dir template = openTempFile' "openBinaryTempFile" tmp_dir template True
422
423 openTempFile' :: String -> FilePath -> String -> Bool -> IO (FilePath, Handle)
424 openTempFile' loc tmp_dir template binary = do
425   pid <- c_getpid
426   findTempName pid
427   where
428     -- We split off the last extension, so we can use .foo.ext files
429     -- for temporary files (hidden on Unix OSes). Unfortunately we're
430     -- below filepath in the hierarchy here.
431     (prefix,suffix) = case break (== '.') $ reverse template of
432                           (rev_suffix, rev_prefix) ->
433                               (reverse rev_prefix, reverse rev_suffix)
434
435     oflags1 = rw_flags .|. o_EXCL
436
437     binary_flags
438       | binary    = o_BINARY
439       | otherwise = 0
440
441     oflags = oflags1 .|. binary_flags
442
443     findTempName x = do
444       fd <- withCString filepath $ \ f ->
445               c_open f oflags 0o666
446       if fd < 0 
447        then do
448          errno <- getErrno
449          if errno == eEXIST
450            then findTempName (x+1)
451            else ioError (errnoToIOError loc errno Nothing (Just tmp_dir))
452        else do
453          h <- fdToHandle' fd Nothing False filepath ReadWriteMode True
454                 `catchException` \e -> do c_close fd; throw e
455          return (filepath, h)
456       where
457         filename        = prefix ++ show x ++ suffix
458         filepath        = tmp_dir ++ [pathSeparator] ++ filename
459
460 -- XXX Should use filepath library
461 pathSeparator :: Char
462 #ifdef mingw32_HOST_OS
463 pathSeparator = '\\'
464 #else
465 pathSeparator = '/'
466 #endif
467
468 -- XXX Copied from GHC.Handle
469 std_flags    = o_NONBLOCK   .|. o_NOCTTY
470 output_flags = std_flags    .|. o_CREAT
471 read_flags   = std_flags    .|. o_RDONLY
472 write_flags  = output_flags .|. o_WRONLY
473 rw_flags     = output_flags .|. o_RDWR
474 append_flags = write_flags  .|. o_APPEND
475
476 -- $locking
477 -- Implementations should enforce as far as possible, at least locally to the
478 -- Haskell process, multiple-reader single-writer locking on files.
479 -- That is, /there may either be many handles on the same file which manage
480 -- input, or just one handle on the file which manages output/.  If any
481 -- open or semi-closed handle is managing a file for output, no new
482 -- handle can be allocated for that file.  If any open or semi-closed
483 -- handle is managing a file for input, new handles can only be allocated
484 -- if they do not manage output.  Whether two files are the same is
485 -- implementation-dependent, but they should normally be the same if they
486 -- have the same absolute path name and neither has been renamed, for
487 -- example.
488 --
489 -- /Warning/: the 'readFile' operation holds a semi-closed handle on
490 -- the file until the entire contents of the file have been consumed.
491 -- It follows that an attempt to write to a file (using 'writeFile', for
492 -- example) that was earlier opened by 'readFile' will usually result in
493 -- failure with 'System.IO.Error.isAlreadyInUseError'.
494
495 -- -----------------------------------------------------------------------------
496 -- Utils
497
498 #ifdef __GLASGOW_HASKELL__
499 -- Copied here to avoid recursive dependency with Control.Exception
500 bracket 
501         :: IO a         -- ^ computation to run first (\"acquire resource\")
502         -> (a -> IO b)  -- ^ computation to run last (\"release resource\")
503         -> (a -> IO c)  -- ^ computation to run in-between
504         -> IO c         -- returns the value from the in-between computation
505 bracket before after thing =
506   block (do
507     a <- before 
508     r <- catchException
509            (unblock (thing a))
510            (\e -> do { after a; throw e })
511     after a
512     return r
513  )
514 #endif