2 -- XXX We get some warnings on Windows
4 -----------------------------------------------------------------------------
6 -- Module : System.Directory
7 -- Copyright : (c) The University of Glasgow 2001
8 -- License : BSD-style (see the file libraries/base/LICENSE)
10 -- Maintainer : libraries@haskell.org
12 -- Portability : portable
14 -- System-independent interface to directory manipulation.
16 -----------------------------------------------------------------------------
18 module System.Directory
22 -- * Actions on directories
23 createDirectory -- :: FilePath -> IO ()
24 , createDirectoryIfMissing -- :: Bool -> FilePath -> IO ()
25 , removeDirectory -- :: FilePath -> IO ()
26 , removeDirectoryRecursive -- :: FilePath -> IO ()
27 , renameDirectory -- :: FilePath -> FilePath -> IO ()
29 , getDirectoryContents -- :: FilePath -> IO [FilePath]
30 , getCurrentDirectory -- :: IO FilePath
31 , setCurrentDirectory -- :: FilePath -> IO ()
33 -- * Pre-defined directories
35 , getAppUserDataDirectory
36 , getUserDocumentsDirectory
37 , getTemporaryDirectory
40 , removeFile -- :: FilePath -> IO ()
41 , renameFile -- :: FilePath -> FilePath -> IO ()
42 , copyFile -- :: FilePath -> FilePath -> IO ()
45 , makeRelativeToCurrentDirectory
49 , doesFileExist -- :: FilePath -> IO Bool
50 , doesDirectoryExist -- :: FilePath -> IO Bool
58 readable, -- :: Permissions -> Bool
59 writable, -- :: Permissions -> Bool
60 executable, -- :: Permissions -> Bool
61 searchable -- :: Permissions -> Bool
64 , getPermissions -- :: FilePath -> IO Permissions
65 , setPermissions -- :: FilePath -> Permissions -> IO ()
69 , getModificationTime -- :: FilePath -> IO ClockTime
72 import Prelude hiding ( catch )
73 import qualified Prelude
75 import Control.Monad (guard)
76 import System.Environment ( getEnv )
77 import System.FilePath
79 import System.IO.Error hiding ( catch, try )
80 import Control.Monad ( when, unless )
81 import Control.Exception.Base
84 import Directory hiding ( getDirectoryContents
85 , doesDirectoryExist, doesFileExist
86 , getModificationTime )
87 import System (system)
97 {-# CFILES cbits/directory.c #-}
99 import System.Posix.Types
100 import System.Posix.Internals
101 import System.Time ( ClockTime(..) )
103 #ifdef __GLASGOW_HASKELL__
104 import GHC.IOBase ( IOException(..), IOErrorType(..), ioException )
106 #ifdef mingw32_HOST_OS
107 import qualified System.Win32
109 import qualified System.Posix
113 A directory contains a series of entries, each of which is a named
114 reference to a file system object (file, directory etc.). Some
115 entries may be hidden, inaccessible, or have some administrative
116 function (e.g. `.' or `..' under POSIX
117 <http://www.opengroup.org/onlinepubs/009695399/>), but in
118 this standard all such entries are considered to form part of the
119 directory contents. Entries in sub-directories are not, however,
120 considered to form part of the directory contents.
122 Each file system object is referenced by a /path/. There is
123 normally at least one absolute path to each file system object. In
124 some operating systems, it may also be possible to have paths which
125 are relative to the current directory.
128 -----------------------------------------------------------------------------
133 The 'Permissions' type is used to record whether certain operations are
134 permissible on a file\/directory. 'getPermissions' and 'setPermissions'
135 get and set these permissions, respectively. Permissions apply both to
136 files and directories. For directories, the executable field will be
137 'False', and for files the searchable field will be 'False'. Note that
138 directories may be searchable without being readable, if permission has
139 been given to use them as part of a path, but not to examine the
142 Note that to change some, but not all permissions, a construct on the following lines must be used.
144 > makeReadable f = do
145 > p <- getPermissions f
146 > setPermissions f (p {readable = True})
153 executable, searchable :: Bool
154 } deriving (Eq, Ord, Read, Show)
156 {- |The 'getPermissions' operation returns the
157 permissions for the file or directory.
159 The operation may fail with:
161 * 'isPermissionError' if the user is not permitted to access
164 * 'isDoesNotExistError' if the file or directory does not exist.
168 getPermissions :: FilePath -> IO Permissions
169 getPermissions name = do
170 withCString name $ \s -> do
171 #ifdef mingw32_HOST_OS
172 -- stat() does a better job of guessing the permissions on Windows
173 -- than access() does. e.g. for execute permission, it looks at the
174 -- filename extension :-)
176 -- I tried for a while to do this properly, using the Windows security API,
177 -- and eventually gave up. getPermissions is a flawed API anyway. -- SimonM
178 allocaBytes sizeof_stat $ \ p_stat -> do
179 throwErrnoIfMinus1_ "getPermissions" $ c_stat s p_stat
180 mode <- st_mode p_stat
181 let usr_read = mode .&. s_IRUSR
182 let usr_write = mode .&. s_IWUSR
183 let usr_exec = mode .&. s_IXUSR
184 let is_dir = mode .&. s_IFDIR
187 readable = usr_read /= 0,
188 writable = usr_write /= 0,
189 executable = is_dir == 0 && usr_exec /= 0,
190 searchable = is_dir /= 0 && usr_exec /= 0
194 read_ok <- c_access s r_OK
195 write_ok <- c_access s w_OK
196 exec_ok <- c_access s x_OK
197 withFileStatus "getPermissions" name $ \st -> do
198 is_dir <- isDirectory st
201 readable = read_ok == 0,
202 writable = write_ok == 0,
203 executable = not is_dir && exec_ok == 0,
204 searchable = is_dir && exec_ok == 0
209 {- |The 'setPermissions' operation sets the
210 permissions for the file or directory.
212 The operation may fail with:
214 * 'isPermissionError' if the user is not permitted to set
217 * 'isDoesNotExistError' if the file or directory does not exist.
221 setPermissions :: FilePath -> Permissions -> IO ()
222 setPermissions name (Permissions r w e s) = do
223 allocaBytes sizeof_stat $ \ p_stat -> do
224 withCString name $ \p_name -> do
225 throwErrnoIfMinus1_ "setPermissions" $ do
227 mode <- st_mode p_stat
228 let mode1 = modifyBit r mode s_IRUSR
229 let mode2 = modifyBit w mode1 s_IWUSR
230 let mode3 = modifyBit (e || s) mode2 s_IXUSR
234 modifyBit :: Bool -> CMode -> CMode -> CMode
235 modifyBit False m b = m .&. (complement b)
236 modifyBit True m b = m .|. b
239 copyPermissions :: FilePath -> FilePath -> IO ()
240 copyPermissions source dest = do
241 allocaBytes sizeof_stat $ \ p_stat -> do
242 withCString source $ \p_source -> do
243 withCString dest $ \p_dest -> do
244 throwErrnoIfMinus1_ "copyPermissions" $ c_stat p_source p_stat
245 mode <- st_mode p_stat
246 throwErrnoIfMinus1_ "copyPermissions" $ c_chmod p_dest mode
248 -----------------------------------------------------------------------------
251 {- |@'createDirectory' dir@ creates a new directory @dir@ which is
252 initially empty, or as near to empty as the operating system
255 The operation may fail with:
257 * 'isPermissionError' \/ 'PermissionDenied'
258 The process has insufficient privileges to perform the operation.
261 * 'isAlreadyExistsError' \/ 'AlreadyExists'
262 The operand refers to a directory that already exists.
266 A physical I\/O error has occurred.
270 The operand is not a valid directory name.
271 @[ENAMETOOLONG, ELOOP]@
274 There is no path to the directory.
277 * 'ResourceExhausted'
278 Insufficient resources (virtual memory, process file descriptors,
279 physical disk space, etc.) are available to perform the operation.
280 @[EDQUOT, ENOSPC, ENOMEM, EMLINK]@
282 * 'InappropriateType'
283 The path refers to an existing non-directory object.
288 createDirectory :: FilePath -> IO ()
289 createDirectory path = do
290 #ifdef mingw32_HOST_OS
291 System.Win32.createDirectory path Nothing
293 System.Posix.createDirectory path 0o777
296 #else /* !__GLASGOW_HASKELL__ */
298 copyPermissions :: FilePath -> FilePath -> IO ()
299 copyPermissions fromFPath toFPath
300 = getPermissions fromFPath >>= setPermissions toFPath
304 -- | @'createDirectoryIfMissing' parents dir@ creates a new directory
305 -- @dir@ if it doesn\'t exist. If the first argument is 'True'
306 -- the function will also create all parent directories if they are missing.
307 createDirectoryIfMissing :: Bool -- ^ Create its parents too?
308 -> FilePath -- ^ The path to the directory you want to make
310 createDirectoryIfMissing create_parents path0
311 | create_parents = createDirs (parents path0)
312 | otherwise = createDirs (take 1 (parents path0))
314 parents = reverse . scanl1 (</>) . splitDirectories . normalise
316 createDirs [] = return ()
317 createDirs (dir:[]) = createDir dir throw
318 createDirs (dir:dirs) =
319 createDir dir $ \_ -> do
323 createDir :: FilePath -> (IOException -> IO ()) -> IO ()
324 createDir dir notExistHandler = do
325 r <- try $ createDirectory dir
326 case (r :: Either IOException ()) of
327 Right () -> return ()
329 | isDoesNotExistError e -> notExistHandler e
330 -- createDirectory (and indeed POSIX mkdir) does not distinguish
331 -- between a dir already existing and a file already existing. So we
332 -- check for it here. Unfortunately there is a slight race condition
333 -- here, but we think it is benign. It could report an exeption in
334 -- the case that the dir did exist but another process deletes the
335 -- directory and creates a file in its place before we can check
336 -- that the directory did indeed exist.
337 | isAlreadyExistsError e ->
338 (withFileStatus "createDirectoryIfMissing" dir $ \st -> do
339 isDir <- isDirectory st
340 if isDir then return ()
342 ) `catch` ((\_ -> return ()) :: IOException -> IO ())
343 | otherwise -> throw e
345 #if __GLASGOW_HASKELL__
346 {- | @'removeDirectory' dir@ removes an existing directory /dir/. The
347 implementation may specify additional constraints which must be
348 satisfied before a directory can be removed (e.g. the directory has to
349 be empty, or may not be in use by other processes). It is not legal
350 for an implementation to partially remove a directory unless the
351 entire directory is removed. A conformant implementation need not
352 support directory removal in all situations (e.g. removal of the root
355 The operation may fail with:
358 A physical I\/O error has occurred.
362 The operand is not a valid directory name.
363 [ENAMETOOLONG, ELOOP]
365 * 'isDoesNotExistError' \/ 'NoSuchThing'
366 The directory does not exist.
369 * 'isPermissionError' \/ 'PermissionDenied'
370 The process has insufficient privileges to perform the operation.
371 @[EROFS, EACCES, EPERM]@
373 * 'UnsatisfiedConstraints'
374 Implementation-dependent constraints are not satisfied.
375 @[EBUSY, ENOTEMPTY, EEXIST]@
377 * 'UnsupportedOperation'
378 The implementation does not support removal in this situation.
381 * 'InappropriateType'
382 The operand refers to an existing non-directory object.
387 removeDirectory :: FilePath -> IO ()
388 removeDirectory path =
389 #ifdef mingw32_HOST_OS
390 System.Win32.removeDirectory path
392 System.Posix.removeDirectory path
397 -- | @'removeDirectoryRecursive' dir@ removes an existing directory /dir/
398 -- together with its content and all subdirectories. Be careful,
399 -- if the directory contains symlinks, the function will follow them.
400 removeDirectoryRecursive :: FilePath -> IO ()
401 removeDirectoryRecursive startLoc = do
402 cont <- getDirectoryContents startLoc
403 sequence_ [rm (startLoc </> x) | x <- cont, x /= "." && x /= ".."]
404 removeDirectory startLoc
406 rm :: FilePath -> IO ()
407 rm f = do temp <- try (removeFile f)
409 Left e -> do isDir <- doesDirectoryExist f
410 -- If f is not a directory, re-throw the error
411 unless isDir $ throw (e :: SomeException)
412 removeDirectoryRecursive f
415 #if __GLASGOW_HASKELL__
416 {- |'removeFile' /file/ removes the directory entry for an existing file
417 /file/, where /file/ is not itself a directory. The
418 implementation may specify additional constraints which must be
419 satisfied before a file can be removed (e.g. the file may not be in
420 use by other processes).
422 The operation may fail with:
425 A physical I\/O error has occurred.
429 The operand is not a valid file name.
430 @[ENAMETOOLONG, ELOOP]@
432 * 'isDoesNotExistError' \/ 'NoSuchThing'
433 The file does not exist.
436 * 'isPermissionError' \/ 'PermissionDenied'
437 The process has insufficient privileges to perform the operation.
438 @[EROFS, EACCES, EPERM]@
440 * 'UnsatisfiedConstraints'
441 Implementation-dependent constraints are not satisfied.
444 * 'InappropriateType'
445 The operand refers to an existing directory.
450 removeFile :: FilePath -> IO ()
453 System.Win32.deleteFile path
455 System.Posix.removeLink path
458 {- |@'renameDirectory' old new@ changes the name of an existing
459 directory from /old/ to /new/. If the /new/ directory
460 already exists, it is atomically replaced by the /old/ directory.
461 If the /new/ directory is neither the /old/ directory nor an
462 alias of the /old/ directory, it is removed as if by
463 'removeDirectory'. A conformant implementation need not support
464 renaming directories in all situations (e.g. renaming to an existing
465 directory, or across different physical devices), but the constraints
468 On Win32 platforms, @renameDirectory@ fails if the /new/ directory already
471 The operation may fail with:
474 A physical I\/O error has occurred.
478 Either operand is not a valid directory name.
479 @[ENAMETOOLONG, ELOOP]@
481 * 'isDoesNotExistError' \/ 'NoSuchThing'
482 The original directory does not exist, or there is no path to the target.
485 * 'isPermissionError' \/ 'PermissionDenied'
486 The process has insufficient privileges to perform the operation.
487 @[EROFS, EACCES, EPERM]@
489 * 'ResourceExhausted'
490 Insufficient resources are available to perform the operation.
491 @[EDQUOT, ENOSPC, ENOMEM, EMLINK]@
493 * 'UnsatisfiedConstraints'
494 Implementation-dependent constraints are not satisfied.
495 @[EBUSY, ENOTEMPTY, EEXIST]@
497 * 'UnsupportedOperation'
498 The implementation does not support renaming in this situation.
501 * 'InappropriateType'
502 Either path refers to an existing non-directory object.
507 renameDirectory :: FilePath -> FilePath -> IO ()
508 renameDirectory opath npath =
509 -- XXX this test isn't performed atomically with the following rename
510 withFileStatus "renameDirectory" opath $ \st -> do
511 is_dir <- isDirectory st
513 then ioException (ioeSetErrorString
514 (mkIOError InappropriateType "renameDirectory" Nothing (Just opath))
517 #ifdef mingw32_HOST_OS
518 System.Win32.moveFileEx opath npath System.Win32.mOVEFILE_REPLACE_EXISTING
520 System.Posix.rename opath npath
523 {- |@'renameFile' old new@ changes the name of an existing file system
524 object from /old/ to /new/. If the /new/ object already
525 exists, it is atomically replaced by the /old/ object. Neither
526 path may refer to an existing directory. A conformant implementation
527 need not support renaming files in all situations (e.g. renaming
528 across different physical devices), but the constraints must be
531 The operation may fail with:
534 A physical I\/O error has occurred.
538 Either operand is not a valid file name.
539 @[ENAMETOOLONG, ELOOP]@
541 * 'isDoesNotExistError' \/ 'NoSuchThing'
542 The original file does not exist, or there is no path to the target.
545 * 'isPermissionError' \/ 'PermissionDenied'
546 The process has insufficient privileges to perform the operation.
547 @[EROFS, EACCES, EPERM]@
549 * 'ResourceExhausted'
550 Insufficient resources are available to perform the operation.
551 @[EDQUOT, ENOSPC, ENOMEM, EMLINK]@
553 * 'UnsatisfiedConstraints'
554 Implementation-dependent constraints are not satisfied.
557 * 'UnsupportedOperation'
558 The implementation does not support renaming in this situation.
561 * 'InappropriateType'
562 Either path refers to an existing directory.
563 @[ENOTDIR, EISDIR, EINVAL, EEXIST, ENOTEMPTY]@
567 renameFile :: FilePath -> FilePath -> IO ()
568 renameFile opath npath =
569 -- XXX this test isn't performed atomically with the following rename
570 withFileOrSymlinkStatus "renameFile" opath $ \st -> do
571 is_dir <- isDirectory st
573 then ioException (ioeSetErrorString
574 (mkIOError InappropriateType "renameFile" Nothing (Just opath))
577 #ifdef mingw32_HOST_OS
578 System.Win32.moveFileEx opath npath System.Win32.mOVEFILE_REPLACE_EXISTING
580 System.Posix.rename opath npath
583 #endif /* __GLASGOW_HASKELL__ */
585 {- |@'copyFile' old new@ copies the existing file from /old/ to /new/.
586 If the /new/ file already exists, it is atomically replaced by the /old/ file.
587 Neither path may refer to an existing directory. The permissions of /old/ are
588 copied to /new/, if possible.
591 copyFile :: FilePath -> FilePath -> IO ()
593 copyFile fromFPath toFPath =
594 do readFile fromFPath >>= writeFile toFPath
595 Prelude.catch (copyPermissions fromFPath toFPath)
598 copyFile fromFPath toFPath =
599 copy `Prelude.catch` (\exc -> throw $ ioeSetLocation exc "copyFile")
600 where copy = bracket (openBinaryFile fromFPath ReadMode) hClose $ \hFrom ->
601 bracketOnError openTmp cleanTmp $ \(tmpFPath, hTmp) ->
602 do allocaBytes bufferSize $ copyContents hFrom hTmp
604 ignoreIOExceptions $ copyPermissions fromFPath tmpFPath
605 renameFile tmpFPath toFPath
606 openTmp = openBinaryTempFile (takeDirectory toFPath) ".copyFile.tmp"
607 cleanTmp (tmpFPath, hTmp)
608 = do ignoreIOExceptions $ hClose hTmp
609 ignoreIOExceptions $ removeFile tmpFPath
612 copyContents hFrom hTo buffer = do
613 count <- hGetBuf hFrom buffer bufferSize
614 when (count > 0) $ do
615 hPutBuf hTo buffer count
616 copyContents hFrom hTo buffer
618 ignoreIOExceptions io = io `catch` ioExceptionIgnorer
619 ioExceptionIgnorer :: IOException -> IO ()
620 ioExceptionIgnorer _ = return ()
623 -- | Given path referring to a file or directory, returns a
624 -- canonicalized path, with the intent that two paths referring
625 -- to the same file\/directory will map to the same canonicalized
626 -- path. Note that it is impossible to guarantee that the
627 -- implication (same file\/dir \<=\> same canonicalizedPath) holds
628 -- in either direction: this function can make only a best-effort
630 canonicalizePath :: FilePath -> IO FilePath
631 canonicalizePath fpath =
632 withCString fpath $ \pInPath ->
633 allocaBytes long_path_size $ \pOutPath ->
634 #if defined(mingw32_HOST_OS)
635 alloca $ \ppFilePart ->
636 do c_GetFullPathName pInPath (fromIntegral long_path_size) pOutPath ppFilePart
638 do c_realpath pInPath pOutPath
640 path <- peekCString pOutPath
641 return (normalise path)
642 -- normalise does more stuff, like upper-casing the drive letter
644 #if defined(mingw32_HOST_OS)
645 foreign import stdcall unsafe "GetFullPathNameA"
646 c_GetFullPathName :: CString
652 foreign import ccall unsafe "realpath"
653 c_realpath :: CString
658 -- | 'makeRelative' the current directory.
659 makeRelativeToCurrentDirectory :: FilePath -> IO FilePath
660 makeRelativeToCurrentDirectory x = do
661 cur <- getCurrentDirectory
662 return $ makeRelative cur x
664 -- | Given an executable file name, searches for such file
665 -- in the directories listed in system PATH. The returned value
666 -- is the path to the found executable or Nothing if there isn't
667 -- such executable. For example (findExecutable \"ghc\")
668 -- gives you the path to GHC.
669 findExecutable :: String -> IO (Maybe FilePath)
670 findExecutable binary =
671 #if defined(mingw32_HOST_OS)
672 withCString binary $ \c_binary ->
673 withCString ('.':exeExtension) $ \c_ext ->
674 allocaBytes long_path_size $ \pOutPath ->
675 alloca $ \ppFilePart -> do
676 res <- c_SearchPath nullPtr c_binary c_ext (fromIntegral long_path_size) pOutPath ppFilePart
677 if res > 0 && res < fromIntegral long_path_size
678 then do fpath <- peekCString pOutPath
682 foreign import stdcall unsafe "SearchPathA"
683 c_SearchPath :: CString
692 path <- getEnv "PATH"
693 search (splitSearchPath path)
695 fileName = binary <.> exeExtension
697 search :: [FilePath] -> IO (Maybe FilePath)
698 search [] = return Nothing
700 let path = d </> fileName
701 b <- doesFileExist path
702 if b then return (Just path)
708 {- |@'getDirectoryContents' dir@ returns a list of /all/ entries
711 The operation may fail with:
714 A physical I\/O error has occurred.
718 The operand is not a valid directory name.
719 @[ENAMETOOLONG, ELOOP]@
721 * 'isDoesNotExistError' \/ 'NoSuchThing'
722 The directory does not exist.
725 * 'isPermissionError' \/ 'PermissionDenied'
726 The process has insufficient privileges to perform the operation.
729 * 'ResourceExhausted'
730 Insufficient resources are available to perform the operation.
733 * 'InappropriateType'
734 The path refers to an existing non-directory object.
739 getDirectoryContents :: FilePath -> IO [FilePath]
740 getDirectoryContents path = do
741 modifyIOError (`ioeSetFileName` path) $
742 alloca $ \ ptr_dEnt ->
744 (withCString path $ \s ->
745 throwErrnoIfNullRetry desc (c_opendir s))
746 (\p -> throwErrnoIfMinus1_ desc (c_closedir p))
747 (\p -> loop ptr_dEnt p)
749 desc = "getDirectoryContents"
751 loop :: Ptr (Ptr CDirent) -> Ptr CDir -> IO [String]
752 loop ptr_dEnt dir = do
754 r <- readdir dir ptr_dEnt
757 dEnt <- peek ptr_dEnt
761 entry <- (d_name dEnt >>= peekCString)
763 entries <- loop ptr_dEnt dir
764 return (entry:entries)
765 else do errno <- getErrno
766 if (errno == eINTR) then loop ptr_dEnt dir else do
767 let (Errno eo) = errno
768 if (eo == end_of_dir)
771 #endif /* !__HUGS__ */
774 {- |If the operating system has a notion of current directories,
775 'getCurrentDirectory' returns an absolute path to the
776 current directory of the calling process.
778 The operation may fail with:
781 A physical I\/O error has occurred.
784 * 'isDoesNotExistError' \/ 'NoSuchThing'
785 There is no path referring to the current directory.
786 @[EPERM, ENOENT, ESTALE...]@
788 * 'isPermissionError' \/ 'PermissionDenied'
789 The process has insufficient privileges to perform the operation.
792 * 'ResourceExhausted'
793 Insufficient resources are available to perform the operation.
795 * 'UnsupportedOperation'
796 The operating system has no notion of current directory.
799 #ifdef __GLASGOW_HASKELL__
800 getCurrentDirectory :: IO FilePath
801 getCurrentDirectory = do
802 #ifdef mingw32_HOST_OS
803 System.Win32.getCurrentDirectory
805 System.Posix.getWorkingDirectory
808 {- |If the operating system has a notion of current directories,
809 @'setCurrentDirectory' dir@ changes the current
810 directory of the calling process to /dir/.
812 The operation may fail with:
815 A physical I\/O error has occurred.
819 The operand is not a valid directory name.
820 @[ENAMETOOLONG, ELOOP]@
822 * 'isDoesNotExistError' \/ 'NoSuchThing'
823 The directory does not exist.
826 * 'isPermissionError' \/ 'PermissionDenied'
827 The process has insufficient privileges to perform the operation.
830 * 'UnsupportedOperation'
831 The operating system has no notion of current directory, or the
832 current directory cannot be dynamically changed.
834 * 'InappropriateType'
835 The path refers to an existing non-directory object.
840 setCurrentDirectory :: FilePath -> IO ()
841 setCurrentDirectory path =
842 #ifdef mingw32_HOST_OS
843 System.Win32.setCurrentDirectory path
845 System.Posix.changeWorkingDirectory path
848 #endif /* __GLASGOW_HASKELL__ */
851 {- |The operation 'doesDirectoryExist' returns 'True' if the argument file
852 exists and is a directory, and 'False' otherwise.
855 doesDirectoryExist :: FilePath -> IO Bool
856 doesDirectoryExist name =
857 (withFileStatus "doesDirectoryExist" name $ \st -> isDirectory st)
858 `catch` ((\ _ -> return False) :: IOException -> IO Bool)
860 {- |The operation 'doesFileExist' returns 'True'
861 if the argument file exists and is not a directory, and 'False' otherwise.
864 doesFileExist :: FilePath -> IO Bool
866 (withFileStatus "doesFileExist" name $ \st -> do b <- isDirectory st; return (not b))
867 `catch` ((\ _ -> return False) :: IOException -> IO Bool)
869 {- |The 'getModificationTime' operation returns the
870 clock time at which the file or directory was last modified.
872 The operation may fail with:
874 * 'isPermissionError' if the user is not permitted to access
875 the modification time; or
877 * 'isDoesNotExistError' if the file or directory does not exist.
881 getModificationTime :: FilePath -> IO ClockTime
882 getModificationTime name =
883 withFileStatus "getModificationTime" name $ \ st ->
886 #endif /* !__HUGS__ */
888 withFileStatus :: String -> FilePath -> (Ptr CStat -> IO a) -> IO a
889 withFileStatus loc name f = do
890 modifyIOError (`ioeSetFileName` name) $
891 allocaBytes sizeof_stat $ \p ->
892 withCString (fileNameEndClean name) $ \s -> do
893 throwErrnoIfMinus1Retry_ loc (c_stat s p)
896 withFileOrSymlinkStatus :: String -> FilePath -> (Ptr CStat -> IO a) -> IO a
897 withFileOrSymlinkStatus loc name f = do
898 modifyIOError (`ioeSetFileName` name) $
899 allocaBytes sizeof_stat $ \p ->
900 withCString name $ \s -> do
901 throwErrnoIfMinus1Retry_ loc (lstat s p)
904 modificationTime :: Ptr CStat -> IO ClockTime
905 modificationTime stat = do
906 mtime <- st_mtime stat
907 let realToInteger = round . realToFrac :: Real a => a -> Integer
908 return (TOD (realToInteger (mtime :: CTime)) 0)
910 isDirectory :: Ptr CStat -> IO Bool
911 isDirectory stat = do
913 return (s_isdir mode)
915 fileNameEndClean :: String -> String
916 fileNameEndClean name = if isDrive name then addTrailingPathSeparator name
917 else dropTrailingPathSeparator name
919 foreign import ccall unsafe "__hscore_R_OK" r_OK :: CInt
920 foreign import ccall unsafe "__hscore_W_OK" w_OK :: CInt
921 foreign import ccall unsafe "__hscore_X_OK" x_OK :: CInt
923 foreign import ccall unsafe "__hscore_S_IRUSR" s_IRUSR :: CMode
924 foreign import ccall unsafe "__hscore_S_IWUSR" s_IWUSR :: CMode
925 foreign import ccall unsafe "__hscore_S_IXUSR" s_IXUSR :: CMode
926 #ifdef mingw32_HOST_OS
927 foreign import ccall unsafe "__hscore_S_IFDIR" s_IFDIR :: CMode
931 #ifdef __GLASGOW_HASKELL__
932 foreign import ccall unsafe "__hscore_long_path_size"
933 long_path_size :: Int
935 long_path_size :: Int
936 long_path_size = 2048 -- // guess?
937 #endif /* __GLASGOW_HASKELL__ */
939 {- | Returns the current user's home directory.
941 The directory returned is expected to be writable by the current user,
942 but note that it isn't generally considered good practice to store
943 application-specific data here; use 'getAppUserDataDirectory'
946 On Unix, 'getHomeDirectory' returns the value of the @HOME@
947 environment variable. On Windows, the system is queried for a
948 suitable path; a typical path might be
949 @C:/Documents And Settings/user@.
951 The operation may fail with:
953 * 'UnsupportedOperation'
954 The operating system has no notion of home directory.
956 * 'isDoesNotExistError'
957 The home directory for the current user does not exist, or
960 getHomeDirectory :: IO FilePath
962 #if defined(mingw32_HOST_OS)
963 allocaBytes long_path_size $ \pPath -> do
964 r0 <- c_SHGetFolderPath nullPtr csidl_PROFILE nullPtr 0 pPath
967 r1 <- c_SHGetFolderPath nullPtr csidl_WINDOWS nullPtr 0 pPath
968 when (r1 < 0) (raiseUnsupported "System.Directory.getHomeDirectory")
975 {- | Returns the pathname of a directory in which application-specific
976 data for the current user can be stored. The result of
977 'getAppUserDataDirectory' for a given application is specific to
980 The argument should be the name of the application, which will be used
981 to construct the pathname (so avoid using unusual characters that
982 might result in an invalid pathname).
984 Note: the directory may not actually exist, and may need to be created
985 first. It is expected that the parent directory exists and is
988 On Unix, this function returns @$HOME\/.appName@. On Windows, a
989 typical path might be
991 > C:/Documents And Settings/user/Application Data/appName
993 The operation may fail with:
995 * 'UnsupportedOperation'
996 The operating system has no notion of application-specific data directory.
998 * 'isDoesNotExistError'
999 The home directory for the current user does not exist, or
1002 getAppUserDataDirectory :: String -> IO FilePath
1003 getAppUserDataDirectory appName = do
1004 #if defined(mingw32_HOST_OS)
1005 allocaBytes long_path_size $ \pPath -> do
1006 r <- c_SHGetFolderPath nullPtr csidl_APPDATA nullPtr 0 pPath
1007 when (r<0) (raiseUnsupported "System.Directory.getAppUserDataDirectory")
1008 s <- peekCString pPath
1009 return (s++'\\':appName)
1011 path <- getEnv "HOME"
1012 return (path++'/':'.':appName)
1015 {- | Returns the current user's document directory.
1017 The directory returned is expected to be writable by the current user,
1018 but note that it isn't generally considered good practice to store
1019 application-specific data here; use 'getAppUserDataDirectory'
1022 On Unix, 'getUserDocumentsDirectory' returns the value of the @HOME@
1023 environment variable. On Windows, the system is queried for a
1024 suitable path; a typical path might be
1025 @C:\/Documents and Settings\/user\/My Documents@.
1027 The operation may fail with:
1029 * 'UnsupportedOperation'
1030 The operating system has no notion of document directory.
1032 * 'isDoesNotExistError'
1033 The document directory for the current user does not exist, or
1036 getUserDocumentsDirectory :: IO FilePath
1037 getUserDocumentsDirectory = do
1038 #if defined(mingw32_HOST_OS)
1039 allocaBytes long_path_size $ \pPath -> do
1040 r <- c_SHGetFolderPath nullPtr csidl_PERSONAL nullPtr 0 pPath
1041 when (r<0) (raiseUnsupported "System.Directory.getUserDocumentsDirectory")
1047 {- | Returns the current directory for temporary files.
1049 On Unix, 'getTemporaryDirectory' returns the value of the @TMPDIR@
1050 environment variable or \"\/tmp\" if the variable isn\'t defined.
1051 On Windows, the function checks for the existence of environment variables in
1052 the following order and uses the first path found:
1055 TMP environment variable.
1058 TEMP environment variable.
1061 USERPROFILE environment variable.
1064 The Windows directory
1066 The operation may fail with:
1068 * 'UnsupportedOperation'
1069 The operating system has no notion of temporary directory.
1071 The function doesn\'t verify whether the path exists.
1073 getTemporaryDirectory :: IO FilePath
1074 getTemporaryDirectory = do
1075 #if defined(mingw32_HOST_OS)
1076 System.Win32.getTemporaryDirectory
1080 `Prelude.catch` \e -> if isDoesNotExistError e then return "/tmp"
1083 `Prelude.catch` (\ex -> return "/tmp")
1087 #if defined(mingw32_HOST_OS)
1088 foreign import ccall unsafe "__hscore_getFolderPath"
1089 c_SHGetFolderPath :: Ptr ()
1095 foreign import ccall unsafe "__hscore_CSIDL_PROFILE" csidl_PROFILE :: CInt
1096 foreign import ccall unsafe "__hscore_CSIDL_APPDATA" csidl_APPDATA :: CInt
1097 foreign import ccall unsafe "__hscore_CSIDL_WINDOWS" csidl_WINDOWS :: CInt
1098 foreign import ccall unsafe "__hscore_CSIDL_PERSONAL" csidl_PERSONAL :: CInt
1100 raiseUnsupported :: String -> IO ()
1101 raiseUnsupported loc =
1102 ioException (ioeSetErrorString (mkIOError UnsupportedOperation loc Nothing Nothing) "unsupported operation")
1106 -- ToDo: This should be determined via autoconf (AC_EXEEXT)
1107 -- | Extension for executable files
1108 -- (typically @\"\"@ on Unix and @\"exe\"@ on Windows or OS\/2)
1109 exeExtension :: String
1110 #ifdef mingw32_HOST_OS
1111 exeExtension = "exe"