By using withCurrentDirectory function,
you can run an IO action with the given working directory and restore the
original working directory afterwards. Following is the signature of withCurrentDirectory
function.
Prelude System.Directory> :t
withCurrentDirectory
withCurrentDirectory :: FilePath ->
IO a -> IO a
Example
1
import System.IO import System.Directory main = do currentDir <- getCurrentDirectory putStrLn $ "Curren working directory is : " ++ currentDir putStrLn "Enter directory name" dir <- getLine result <- withCurrentDirectory dir getCurrentDirectory putStrLn $ "Curren working directory is changed to : " ++ result currentDire <- getCurrentDirectory putStrLn $ "Curren working directory is changed back to: " ++ currentDir
$ runghc DirectoryUtil.hs Curren working directory is : /Users/harikrishna_gurram/study1/Haskell/programs Enter directory name /Users Curren working directory is changed to : /Users Curren working directory is changed back to: /Users/harikrishna_gurram/study1/Haskell/programs localhost:programs harikrishna_gurram$
Example 2
DirectoryUtil.hs
import System.IO import System.Directory listContents = do currentDir <- getCurrentDirectory putStrLn $ "Current working directory is changed to :" ++ currentDir listDirectory currentDir main = do currentDir <- getCurrentDirectory putStrLn $ "Current working directory is : " ++ currentDir putStrLn "Enter directory name" dir <- getLine result <- withCurrentDirectory dir listContents putStrLn $ "Contents of given directory " ++ (show result) currentDire <- getCurrentDirectory putStrLn $ "Current working directory is changed back to : " ++ currentDir
$ runghc DirectoryUtil.hs Current working directory is : /Users/harikrishna_gurram/study1/Haskell/programs Enter directory name /Users Current working directory is changed to :/Users Contents of given directory [".localized","harikrishna_gurram","Shared"] Current working directory is changed back to : /Users/harikrishna_gurram/study1/Haskell/programs
No comments:
Post a Comment