Monday 30 May 2016

Haskell: setCurrentDirectory: Change working directory

System.Directory module provides setCurrentDirectory function to change current working directory. Following is the signature of setCurrentDirectory function.

Prelude System.Directory> :t setCurrentDirectory
setCurrentDirectory :: FilePath -> IO ()

As per documentation, you may get following error while working with setCurrentDirectory.

Error
Description
HardwareFault
A physical I/O error has occurred.
InvalidArgument
The operand is not a valid directory name.
isDoesNotExistError or NoSuchThing
The directory does not exist.
isPermissionError or PermissionDenied
The process has insufficient privileges to perform the operation.
UnsupportedOperation
The operating system has no notion of current working directory, or the working directory cannot be dynamically changed.
InappropriateType
The path refers to an existing non-directory object.


DirectoryUtil.hs
import System.IO
import System.Directory

main = do
    currentDir <- getCurrentDirectory 
    putStrLn $ "Current working directory: " ++ currentDir

    putStrLn "Enter the new location"
    newLoc <- getLine

    putStrLn $ "Changind current working directory from " ++ currentDir ++ " to " ++ newLoc
    setCurrentDirectory newLoc

    currentDir <- getCurrentDirectory 
    putStrLn $ "Current working directory: " ++ currentDir

$ runghc DirectoryUtil.hs 
Current working directory: /Users/harikrishna_gurram/study1/Haskell/programs
Enter the new location
/Users/harikrishna_gurram/shared
Changind current working directory from /Users/harikrishna_gurram/study1/Haskell/programs to /Users/harikrishna_gurram/shared
Current working directory: /Users/harikrishna_gurram/shared

Note
From ghci prompt, you can change the current working directory using :cd command.
Usually GHCi can able to see the source files in whatever directory it was run. To change the source directory use ‘:cd’ command.


Prelude> :cd {PATH TO YOUR SOURCE DIRECTORY}


Previous                                                 Next                                                 Home

No comments:

Post a Comment