Thursday, 2 June 2016

Haskell: findFilesWith: Get all the files that satisfiy given property

System.Directory module provides findFilesWith function, Search through the given set of directories for the given file and with the given property (usually permissions) and returns a list of paths where the given file exists and has the property. Following is the signature of findFilesWith function.

findFilesWith :: (FilePath -> IO Bool) -> [FilePath] -> String -> IO [FilePath]

Following program takes list of directories and a file name to search, return all the paths where this file is executable.

DirectoryUtil.hs
import System.IO
import System.Directory
import Data.List.Split

getExecutablePaths listOfDirs file =
    findFilesWith isExecutable listOfDirs file
        where isExecutable file = do
         perms <- getPermissions file
         return $ executable perms

main = do
 putStrLn "Enter the directories to search (, separated)"
 directories <- getLine

 putStrLn "Enter file to search"
 file <- getLine

 let listOfDirs = (splitOn "," directories)

 executables <- getExecutablePaths listOfDirs file

 putStrLn (show executables)

$ runghc DirectoryUtil.hs
Enter the directories to search (, separated)
/usr/bin,/var,/Users,/bin,/Users/harikrishna_gurram
Enter file to search
java
["/usr/bin/java","/bin/java"]



Previous                                                 Next                                                 Home

No comments:

Post a Comment