
``  Directory Scanner Class
``  Scriptol - (c) 2001-2008  Denis Sureau
``  www.scriptol.com

``  This is a wrapper to directory content reading
``  The path separator is "/" under Unix and Windows


include "path.sol"


class DirList is Path

 dyn handle = 0          ` a PHP ressource
 int total = 0
 text name = ""

 ` OPEN - Open a directory
 boolean open(text dpath)
   handle = opendir(dpath)
   name = dpath
 return true


 ` CLOSE - Close the directory
 void close()
  closedir(handle);
 return


 ` NEXT
 ` Get the next filename in the directory and increments the pointer
 ` Return nil if no more file

 text next():   return readdir(handle)


 ` BEGIN - Go to the first entry
 void begin():   rewinddir(handle);  return


 ` GETLIST
 ` Return the list of all filenames in a directory
 ` If the path doesn't exist or is not a directory, return an empty list

 array getList(text dpath)
   array dlist = ()
   if not Path.exists(dpath) ? return dlist
   if Path.type(dpath) <> "dir" ? return dlist
   open(dpath)

   begin()
   do
     text fname = next()
     if fname = nil ? break
     if fname in (".", "..") ? continue
     dlist.push(fname)
   /do forever
   close()
 return dlist


`  DISPDIR
`  Displays the content of a directory with size of files
`  Returns number of files, number of dirs, total size.
 
 int, int, int disp(text dpath)
   total = 0             ` total size of all files
   int files = 0         ` counter of files
   int dirs = 0          ` counter of subdirectories
   text sizestr = ""     ` the size as a string or <dir>

   if not Path.exists(dpath)
     print dpath, "no found"
     exit()
   /if

   if Path.type(dpath) <> "dir" ?  die(dpath + " not a directory")

   open(dpath)       ` open the directory
   begin()           ` move the pointer to the first entry

   do
     text fname = next()                 ` the name of an entry
     text fullname = Path.merge(dpath , fname)
     if fname = nil ? break
     if fname in (".", "..") ? continue  ` ignore these

     if Path.type(fullname)
     = "dir" :              ` if a subdirectory
               sizestr = "<dir>"
               dirs + 1
     = "file" :             ` if a file
               number si = Path.size(fullname)
               sizestr = strval(si)
               files + 1
               total + si   ` add size to total
     else:
               sizestr = "<unknow type>"
     /if
     print pad(fname, 32), pad(sizestr, 9, " ", $(STR_PAD_LEFT))

   /do forever

   close()
   print pad(text(files), 20, " ", $(STR_PAD_LEFT)), "files(s)   ", total, "bytes"
   print pad(text(dirs), 20, " ", $(STR_PAD_LEFT)) , "dir(s)"

 return files, dirs, total

/class

// testing
//Dir mydir
//mydir.dispDir("c:/")
