[Haskell] Reading a directory tree
glynn.clements at virgin.net
Tue Jun 22 11:38:14 EDT 2004
Tom Hofte wrote:
> I'm looking for a way to iteratively read all the files in a directory
> its subdirectories, given the filepath of the top-level dir.
> For example, I want to find a file, corresponding to a given filename,
> in a directory and its subdirectories.
> Is there a way to implement this in Haskell?
This is somewhat simpler than the other examples which have been
> import Monad
> import Directory
> scanDir :: FilePath -> IO [FilePath]
> scanDir dir = do
> names <- getDirectoryContents dir
> let names' = filter ((/= '.') . head) names
> let paths = map ((dir ++ "/") ++) names'
> dirs <- filterM doesDirectoryExist paths
> files <- filterM doesFileExist paths
> rest <- mapM scanDir dirs
> return $ files ++ concat rest
One caveat: (scanDir "/") isn't handled correctly; you will get an
extra slash, i.e. "//usr", "//bin" etc. Not that I'd recommend using
this code for scanning an entire filesystem, due to performance
Glynn Clements <glynn.clements at virgin.net>
More information about the Haskell