Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory contents in Haskell

Is there a way of returning a list of files in a directory with their absolute paths.

When I do

getDirectoryContents dir

it gives me a list of filenames in the directory. If I am using these filenames at another place, I need to know their absolute paths or the paths relative to the current working directory.

like image 554
atlantis Avatar asked Dec 20 '11 07:12

atlantis


2 Answers

getAbsDirectoryContents :: FilePath -> IO [FilePath]
getAbsDirectoryContents dir =
  getDirectoryContents dir >>= mapM (canonicalizePath . (dir </>))

This uses System.Directory.canonicalizePath, and works even if dir is not an absolute path (e.g. if you call getAbsDirectoryContents "foo" and then move elsewhere in the filesystem).

If you know that dir is an absolute path, you can instead use:

getAbsDirectoryContents :: FilePath -> IO [FilePath]
getAbsDirectoryContents dir = map (dir </>) <$> getDirectoryContents dir

which uses System.FilePath.(</>), and might be a bit faster.

like image 130
ehird Avatar answered Nov 09 '22 05:11

ehird


import System.Directory (getDirectoryContents)
import System.FilePath ((</>))

getAbsoluteDirContents :: String -> IO [FilePath]
getAbsoluteDirContents dir = do
  contents <- getDirectoryContents dir
  return $ map (dir </>) contents
like image 28
Paolo Capriotti Avatar answered Nov 09 '22 05:11

Paolo Capriotti