[Haskell-cafe] [Beginner's Question] How to read filenames from a DirStream

Albert Lee hanzhupeng at gmail.com
Mon Apr 9 00:27:28 EDT 2007


Thanks for your reply. and I have done it by:

import System.IO
import System.Posix
import System.Directory

show_current_dir :: IO ()
show_current_dir = do
  curr_dir <- getWorkingDirectory

  putStrLn ("Current Working Directory:" ++ curr_dir)

ls_dir1 :: String -> IO [()]
ls_dir1 fp = do
  files <- getDirectoryContents fp
  putStrLn ("ls_dir1: Files in " ++ fp ++ ":")

  mapM putStrLn files

read_fp_from_DirStream :: DirStream -> IO()
read_fp_from_DirStream dp = do
  f <- readDirStream dp
  if f == "" then return () else do putStrLn f
                                    read_fp_from_DirStream dp


ls_dir2 :: String -> IO ()
ls_dir2 fp = do
  dp <- openDirStream fp
  putStrLn ("ls_dir2: files in " ++ fp ++ ":")
  read_fp_from_DirStream dp
  closeDirStream dp


main :: IO ()
main = do
  putStrLn "Unix programming use Haskell"
  show_current_dir
  ls_dir1 "/"
   ls_dir2 "/home"

-- is that right?

2007/4/9, Alec Berryman <alec at thened.net>:
>
> Albert Lee on 2007-04-09 10:46:14 +0800:
>
> >  I want to ls the filenames of a directory.
>
> [...]
>
> >  and I write that in haskell:
> >
> >  -----
> >  import System.Posix
> >  import System.IO
> >
> >  main = do
> >     dp <- openDirStream "/"
> >     df <- readDirStream dp
> >     putStrLn df
> >     closeDirStream dp
> >
> >
> >  ------
> >  It can print the first entry of the dir, but how can we list it all
> like the
> >  C prog?  map ? list comperhension?
>
> System.Posix is one way to do it, but you might find the functions in
> System.Directory easier to use -  there's a function to get the
> directory contents as a list of strings.  To print them out, you may
> want to look at one of the mapM functions.
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>



-- 
http://hanzhupeng.googlepages.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070409/3cf5afee/attachment.htm


More information about the Haskell-Cafe mailing list