Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Why do input* and readdir throw End_of_file ... annoying!
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Eric C. Cooper <ecc@c...>
Subject: Re: [Caml-list] Why do input* and readdir throw End_of_file ... annoying!
On Fri, Jun 06, 2003 at 07:43:04PM +0100, Richard Jones wrote:
> The problem is that there doesn't seem to be a way to write the
> loop function using readdir. eg:
> 
>   let rec loop () =
>     let filename = readdir dirh in
>     match filename with
>     | "." -> loop ()
>     | ".." -> loop ()
>     | filename ->
> 	let pathname = path ^ "/" ^ filename in
> 	let stat = lstat pathname in
> 	let this = if stat.st_kind = S_DIR then
> 	  read_directory pathname
> 	else
> 	  File pathname in
> 	this :: loop ()
>   in
>   try
>     Directory (loop ())
>   with
>     End_of_file ->  XXX what?
> 
> Because the exception is always raised (it's not an exception at all)
> there's no way to return the result of the call to loop ().

Define your loop to take an accumulator (a list of the results so far):

let rec read_filesystem path =
  if (lstat path).st_kind = S_DIR then
    Directory (read_directory pathname)
  else
    File path

and read_directory path =
  let dirh = opendir path in
  let rec loop entries =
    try match readdir dirh with
    | "." | ".." -> loop entries
    | filename -> loop (read_filesystem filename :: entries)
    with End_of_file -> entries
  in
  let list = loop [] in
  closedir dirh;
  list

-- 
Eric C. Cooper          e c c @ c m u . e d u

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners