FIX #1689 (openTempFile returns wrong filename)
[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 (not portable: GHC\/Hugs only)
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 (not portable: GHC only)
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\/Hugs only)
159
160 #if !defined(__NHC__)
161     openTempFile,
162     openBinaryTempFile,
163 #endif
164   ) where
165
166 #ifndef __NHC__
167 import Data.Bits
168 import Data.List
169 import Data.Maybe
170 import Foreign.C.Error
171 import Foreign.C.String
172 import System.Posix.Internals
173 #endif
174
175 #ifdef __GLASGOW_HASKELL__
176 import GHC.Exception    as ExceptionBase hiding (catch)
177 #endif
178 #ifdef __HUGS__
179 import Hugs.Exception   as ExceptionBase
180 #endif
181
182 #ifdef __GLASGOW_HASKELL__
183 import GHC.Base
184 import GHC.IOBase       -- Together these four Prelude modules define
185 import GHC.Handle       -- all the stuff exported by IO for the GHC version
186 import GHC.IO
187 import GHC.Exception
188 import GHC.Num
189 import GHC.Read
190 import GHC.Show
191 #endif
192
193 #ifdef __HUGS__
194 import Hugs.IO
195 import Hugs.IOExts
196 import Hugs.IORef
197 import Hugs.Prelude     ( throw, Exception(NonTermination) )
198 import Control.Exception ( bracket )
199 import System.IO.Unsafe ( unsafeInterleaveIO )
200 #endif
201
202 #ifdef __NHC__
203 import IO
204   ( Handle ()
205   , HandlePosn ()
206   , IOMode (ReadMode,WriteMode,AppendMode,ReadWriteMode)
207   , BufferMode (NoBuffering,LineBuffering,BlockBuffering)
208   , SeekMode (AbsoluteSeek,RelativeSeek,SeekFromEnd)
209   , stdin, stdout, stderr
210   , openFile                  -- :: FilePath -> IOMode -> IO Handle
211   , hClose                    -- :: Handle -> IO ()
212   , hFileSize                 -- :: Handle -> IO Integer
213   , hIsEOF                    -- :: Handle -> IO Bool
214   , isEOF                     -- :: IO Bool
215   , hSetBuffering             -- :: Handle -> BufferMode -> IO ()
216   , hGetBuffering             -- :: Handle -> IO BufferMode
217   , hFlush                    -- :: Handle -> IO ()
218   , hGetPosn                  -- :: Handle -> IO HandlePosn
219   , hSetPosn                  -- :: HandlePosn -> IO ()
220   , hSeek                     -- :: Handle -> SeekMode -> Integer -> IO ()
221   , hWaitForInput             -- :: Handle -> Int -> IO Bool
222   , hGetChar                  -- :: Handle -> IO Char
223   , hGetLine                  -- :: Handle -> IO [Char]
224   , hLookAhead                -- :: Handle -> IO Char
225   , hGetContents              -- :: Handle -> IO [Char]
226   , hPutChar                  -- :: Handle -> Char -> IO ()
227   , hPutStr                   -- :: Handle -> [Char] -> IO ()
228   , hPutStrLn                 -- :: Handle -> [Char] -> IO ()
229   , hPrint                    -- :: Handle -> [Char] -> IO ()
230   , hReady                    -- :: Handle -> [Char] -> IO ()
231   , hIsOpen, hIsClosed        -- :: Handle -> IO Bool
232   , hIsReadable, hIsWritable  -- :: Handle -> IO Bool
233   , hIsSeekable               -- :: Handle -> IO Bool
234   , bracket
235
236   , IO ()
237   , FilePath                  -- :: String
238   )
239 import NHC.IOExtras (fixIO, hPutBuf, hGetBuf)
240 import NHC.FFI (Ptr)
241 #endif
242
243 -- -----------------------------------------------------------------------------
244 -- Standard IO
245
246 #ifdef __GLASGOW_HASKELL__
247 -- | Write a character to the standard output device
248 -- (same as 'hPutChar' 'stdout').
249
250 putChar         :: Char -> IO ()
251 putChar c       =  hPutChar stdout c
252
253 -- | Write a string to the standard output device
254 -- (same as 'hPutStr' 'stdout').
255
256 putStr          :: String -> IO ()
257 putStr s        =  hPutStr stdout s
258
259 -- | The same as 'putStr', but adds a newline character.
260
261 putStrLn        :: String -> IO ()
262 putStrLn s      =  do putStr s
263                       putChar '\n'
264
265 -- | The 'print' function outputs a value of any printable type to the
266 -- standard output device.
267 -- Printable types are those that are instances of class 'Show'; 'print'
268 -- converts values to strings for output using the 'show' operation and
269 -- adds a newline.
270 --
271 -- For example, a program to print the first 20 integers and their
272 -- powers of 2 could be written as:
273 --
274 -- > main = print ([(n, 2^n) | n <- [0..19]])
275
276 print           :: Show a => a -> IO ()
277 print x         =  putStrLn (show x)
278
279 -- | Read a character from the standard input device
280 -- (same as 'hGetChar' 'stdin').
281
282 getChar         :: IO Char
283 getChar         =  hGetChar stdin
284
285 -- | Read a line from the standard input device
286 -- (same as 'hGetLine' 'stdin').
287
288 getLine         :: IO String
289 getLine         =  hGetLine stdin
290
291 -- | The 'getContents' operation returns all user input as a single string,
292 -- which is read lazily as it is needed
293 -- (same as 'hGetContents' 'stdin').
294
295 getContents     :: IO String
296 getContents     =  hGetContents stdin
297
298 -- | The 'interact' function takes a function of type @String->String@
299 -- as its argument.  The entire input from the standard input device is
300 -- passed to this function as its argument, and the resulting string is
301 -- output on the standard output device.
302
303 interact        ::  (String -> String) -> IO ()
304 interact f      =   do s <- getContents
305                        putStr (f s)
306
307 -- | The 'readFile' function reads a file and
308 -- returns the contents of the file as a string.
309 -- The file is read lazily, on demand, as with 'getContents'.
310
311 readFile        :: FilePath -> IO String
312 readFile name   =  openFile name ReadMode >>= hGetContents
313
314 -- | The computation 'writeFile' @file str@ function writes the string @str@,
315 -- to the file @file@.
316 writeFile :: FilePath -> String -> IO ()
317 writeFile f txt = withFile f WriteMode (\ hdl -> hPutStr hdl txt)
318
319 -- | The computation 'appendFile' @file str@ function appends the string @str@,
320 -- to the file @file@.
321 --
322 -- Note that 'writeFile' and 'appendFile' write a literal string
323 -- to a file.  To write a value of any printable type, as with 'print',
324 -- use the 'show' function to convert the value to a string first.
325 --
326 -- > main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
327
328 appendFile      :: FilePath -> String -> IO ()
329 appendFile f txt = withFile f AppendMode (\ hdl -> hPutStr hdl txt)
330
331 -- | The 'readLn' function combines 'getLine' and 'readIO'.
332
333 readLn          :: Read a => IO a
334 readLn          =  do l <- getLine
335                       r <- readIO l
336                       return r
337
338 -- | The 'readIO' function is similar to 'read' except that it signals
339 -- parse failure to the 'IO' monad instead of terminating the program.
340
341 readIO          :: Read a => String -> IO a
342 readIO s        =  case (do { (x,t) <- reads s ;
343                               ("","") <- lex t ;
344                               return x }) of
345                         [x]    -> return x
346                         []     -> ioError (userError "Prelude.readIO: no parse")
347                         _      -> ioError (userError "Prelude.readIO: ambiguous parse")
348 #endif  /* __GLASGOW_HASKELL__ */
349
350 #ifndef __NHC__
351 -- | Computation 'hReady' @hdl@ indicates whether at least one item is
352 -- available for input from handle @hdl@.
353 -- 
354 -- This operation may fail with:
355 --
356 --  * 'System.IO.Error.isEOFError' if the end of file has been reached.
357
358 hReady          :: Handle -> IO Bool
359 hReady h        =  hWaitForInput h 0
360
361 -- | The same as 'hPutStr', but adds a newline character.
362
363 hPutStrLn       :: Handle -> String -> IO ()
364 hPutStrLn hndl str = do
365  hPutStr  hndl str
366  hPutChar hndl '\n'
367
368 -- | Computation 'hPrint' @hdl t@ writes the string representation of @t@
369 -- given by the 'shows' function to the file or channel managed by @hdl@
370 -- and appends a newline.
371 --
372 -- This operation may fail with:
373 --
374 --  * 'System.IO.Error.isFullError' if the device is full; or
375 --
376 --  * 'System.IO.Error.isPermissionError' if another system resource limit would be exceeded.
377
378 hPrint          :: Show a => Handle -> a -> IO ()
379 hPrint hdl      =  hPutStrLn hdl . show
380 #endif /* !__NHC__ */
381
382 -- | @'withFile' name mode act@ opens a file using 'openFile' and passes
383 -- the resulting handle to the computation @act@.  The handle will be
384 -- closed on exit from 'withFile', whether by normal termination or by
385 -- raising an exception.
386 withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
387 withFile name mode = bracket (openFile name mode) hClose
388
389 -- | @'withBinaryFile' name mode act@ opens a file using 'openBinaryFile'
390 -- and passes the resulting handle to the computation @act@.  The handle
391 -- will be closed on exit from 'withBinaryFile', whether by normal
392 -- termination or by raising an exception.
393 withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
394 withBinaryFile name mode = bracket (openBinaryFile name mode) hClose
395
396 -- ---------------------------------------------------------------------------
397 -- fixIO
398
399 #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__)
400 fixIO :: (a -> IO a) -> IO a
401 fixIO k = do
402     ref <- newIORef (throw NonTermination)
403     ans <- unsafeInterleaveIO (readIORef ref)
404     result <- k ans
405     writeIORef ref result
406     return result
407
408 -- NOTE: we do our own explicit black holing here, because GHC's lazy
409 -- blackholing isn't enough.  In an infinite loop, GHC may run the IO
410 -- computation a few times before it notices the loop, which is wrong.
411 #endif
412
413 #if defined(__NHC__)
414 -- Assume a unix platform, where text and binary I/O are identical.
415 openBinaryFile = openFile
416 hSetBinaryMode _ _ = return ()
417 #endif
418
419 #ifndef __NHC__
420 -- | The function creates a temporary file in ReadWrite mode.
421 -- The created file isn\'t deleted automatically, so you need to delete it manually.
422 openTempFile :: FilePath   -- ^ Directory in which to create the file
423              -> String     -- ^ File name template. If the template is \"foo.ext\" then
424                            -- the created file will be \"fooXXX.ext\" where XXX is some
425                            -- random number.
426              -> IO (FilePath, Handle)
427 openTempFile tmp_dir template = openTempFile' "openTempFile" tmp_dir template False
428
429 -- | Like 'openTempFile', but opens the file in binary mode. See 'openBinaryFile' for more comments.
430 openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle)
431 openBinaryTempFile tmp_dir template = openTempFile' "openBinaryTempFile" tmp_dir template True
432
433 openTempFile' :: String -> FilePath -> String -> Bool -> IO (FilePath, Handle)
434 openTempFile' loc tmp_dir template binary = do
435   pid <- c_getpid
436   findTempName pid
437   where
438     -- We split off the last extension, so we can use .foo.ext files
439     -- for temporary files (hidden on Unix OSes). Unfortunately we're
440     -- below filepath in the hierarchy here.
441     (prefix,suffix) = 
442        case break (== '.') $ reverse template of
443          -- First case: template contains no '.'s. Just re-reverse it.
444          (rev_suffix, "")       -> (reverse rev_suffix, "")
445          -- Second case: template contains at least one '.'. Strip the
446          -- dot from the prefix and prepend it to the suffix (if we don't
447          -- do this, the unique number will get added after the '.' and
448          -- thus be part of the extension, which is wrong.)
449          (rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix)
450          -- Otherwise, something is wrong, because (break (== '.')) should
451          -- always return a pair with either the empty string or a string
452          -- beginning with '.' as the second component.
453          _                      -> error "bug in System.IO.openTempFile"
454
455     oflags1 = rw_flags .|. o_EXCL
456
457     binary_flags
458       | binary    = o_BINARY
459       | otherwise = 0
460
461     oflags = oflags1 .|. binary_flags
462
463     findTempName x = do
464       fd <- withCString filepath $ \ f ->
465               c_open f oflags 0o666
466       if fd < 0 
467        then do
468          errno <- getErrno
469          if errno == eEXIST
470            then findTempName (x+1)
471            else ioError (errnoToIOError loc errno Nothing (Just tmp_dir))
472        else do
473          -- XXX We want to tell fdToHandle what the filepath is,
474          -- as any exceptions etc will only be able to report the
475          -- fd currently
476          h <- fdToHandle fd
477                 `ExceptionBase.catchException` \e -> do c_close fd; throw e
478          return (filepath, h)
479       where
480         filename        = prefix ++ show x ++ suffix
481         filepath        = tmp_dir ++ [pathSeparator] ++ filename
482 #if __HUGS__
483         fdToHandle fd   = openFd (fromIntegral fd) False ReadWriteMode binary
484 #endif
485
486 -- XXX Should use filepath library
487 pathSeparator :: Char
488 #ifdef mingw32_HOST_OS
489 pathSeparator = '\\'
490 #else
491 pathSeparator = '/'
492 #endif
493
494 -- XXX Copied from GHC.Handle
495 std_flags    = o_NONBLOCK   .|. o_NOCTTY
496 output_flags = std_flags    .|. o_CREAT
497 read_flags   = std_flags    .|. o_RDONLY
498 write_flags  = output_flags .|. o_WRONLY
499 rw_flags     = output_flags .|. o_RDWR
500 append_flags = write_flags  .|. o_APPEND
501 #endif
502
503 -- $locking
504 -- Implementations should enforce as far as possible, at least locally to the
505 -- Haskell process, multiple-reader single-writer locking on files.
506 -- That is, /there may either be many handles on the same file which manage
507 -- input, or just one handle on the file which manages output/.  If any
508 -- open or semi-closed handle is managing a file for output, no new
509 -- handle can be allocated for that file.  If any open or semi-closed
510 -- handle is managing a file for input, new handles can only be allocated
511 -- if they do not manage output.  Whether two files are the same is
512 -- implementation-dependent, but they should normally be the same if they
513 -- have the same absolute path name and neither has been renamed, for
514 -- example.
515 --
516 -- /Warning/: the 'readFile' operation holds a semi-closed handle on
517 -- the file until the entire contents of the file have been consumed.
518 -- It follows that an attempt to write to a file (using 'writeFile', for
519 -- example) that was earlier opened by 'readFile' will usually result in
520 -- failure with 'System.IO.Error.isAlreadyInUseError'.
521
522 -- -----------------------------------------------------------------------------
523 -- Utils
524
525 #ifdef __GLASGOW_HASKELL__
526 -- Copied here to avoid recursive dependency with Control.Exception
527 bracket 
528         :: IO a         -- ^ computation to run first (\"acquire resource\")
529         -> (a -> IO b)  -- ^ computation to run last (\"release resource\")
530         -> (a -> IO c)  -- ^ computation to run in-between
531         -> IO c         -- returns the value from the in-between computation
532 bracket before after thing =
533   block (do
534     a <- before 
535     r <- catchException
536            (unblock (thing a))
537            (\e -> do { after a; throw e })
538     after a
539     return r
540  )
541 #endif