Monday, 30 May 2016

Haskell: createDirectoryIfMissing: Create directory if not exist

System.Directory module provides createDirectoryIfMissing function, which creates a directory if it not exists. Following is the signature of the createDirectoryIfMissing function.

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

Observe the signature, createDirectoryIfMissing  function takes two arguments: a Bool variable, FilePath. If the first argument is True the function will also create all parent directories if they are missing.


DirectoryUtil.hs
{- Take directory name as input and create a directory -}
import System.IO
import System.Directory

main = do
    putStrLn "Enter directory name"
    direcotryName <- getLine

    -- Create parent directories also
    createDirectoryIfMissing True direcotryName
    putStrLn "Directory created"

$ du -hc  /Users/harikrishna_gurram/today
du: /Users/harikrishna_gurram/today: No such file or directory
  0B total
$ 
$ runghc DirectoryUtil.hs 
Enter directory name
/Users/harikrishna_gurram/today/evenings/1
Directory created
$ 
$ du -hc  /Users/harikrishna_gurram/today
  0B /Users/harikrishna_gurram/today/evenings/1
  0B /Users/harikrishna_gurram/today/evenings
  0B /Users/harikrishna_gurram/today
  0B total



Previous                                                 Next                                                 Home

No comments:

Post a Comment