atlantis
atlantis

Reputation: 3126

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.

Upvotes: 16

Views: 2106

Answers (2)

ehird
ehird

Reputation: 40787

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.

Upvotes: 16

Paolo Capriotti
Paolo Capriotti

Reputation: 4072

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

getAbsoluteDirContents :: String -> IO [FilePath]
getAbsoluteDirContents dir = do
  contents <- getDirectoryContents dir
  return $ map (dir </>) contents

Upvotes: 3

Related Questions