Monday, 30 May 2016

Haskell: renameFile: Rename file

System.Directory module provides renameFile function, which is used to rename a file. Following is the signature of renameFile function.

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

Example
renameFile oldFile newFile
If the newFile already exists, it is atomically replaced by the oldFile.

You may get following errors while working with renameFile function.

Error
Description
HardwareFault
A physical I/O error has occurred.
InvalidArgument
Either operand is not a valid file name.
isDoesNotExistError / NoSuchThing
The original file does not exist, or there is no path to the target.
isPermissionError / PermissionDenied
The process has insufficient privileges to perform the operation.
ResourceExhausted
Insufficient resources are available to perform the operation.
UnsatisfiedConstraints
Implementation-dependent constraints are not satisfied.
UnsupportedOperation
The implementation does not support renaming in this situation.
InappropriateType
Either path refers to an existing directory.


DirectoryUtil.hs
import System.IO
import System.Directory

main = do
    putStrLn "Enter file path to rename"
    oldFile <- getLine

    putStrLn "Enter new name for the file"
    newFile <- getLine

    renameFile oldFile newFile
    putStrLn "File renamed"

$  ls -l /Users/harikrishna_gurram/admin.log
-rw-r--r--  1 harikrishna_gurram  ABC Users  2367 Apr  2 13:38 /Users/harikrishna_gurram/admin.log
$ 
$ runghc DirectoryUtil.hs 
Enter file path to rename
/Users/harikrishna_gurram/admin.log
Enter new name for the file
/Users/harikrishna_gurram/admin_tmp.log
File renamed
$ 
$  ls -l /Users/harikrishna_gurram/admin.log
ls: /Users/harikrishna_gurram/admin.log: No such file or directory
$
$  ls -l /Users/harikrishna_gurram/admin_tmp.log
-rw-r--r--  1 harikrishna_gurram  ABC Users  2367 Apr  2 13:38 /Users/harikrishna_gurram/admin_tmp.log




Previous                                                 Next                                                 Home

No comments:

Post a Comment