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.
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.
import System.Directory (getDirectoryContents)
import System.FilePath ((</>))
getAbsoluteDirContents :: String -> IO [FilePath]
getAbsoluteDirContents dir = do
contents <- getDirectoryContents dir
return $ map (dir </>) contents
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With