Is there a "list all files" procedure in scheme?

962 Views Asked by At

Is there a racket/scheme procedure that returns a list (or vector) of the names of all user accesible files?
The output needs to be a list or vector for applying a "filter", like so:

(filter pred list-of-all-files)

The intended application is a text-based, user-friendly "librarian" program.

1

There are 1 best solutions below

1
On

The relevant procedures you are looking for are directory-list and in-directory.

Using directory-list, you can retrieve a list of all files and directories in the directory specified by some path (similar to the shell command ls).

;; ls /some/path
(directory-list "/some/path")

On the other hand, in-directory returns a sequence that produces all of the paths for files, directories, and links within a directory, traversing nested subdirectories recursively (which seems to be what you are primarily looking for).

For example, to return the names of all user readable files and directories under "/some/path", you can do:

(for/list ([f (in-directory "/some/path"
                            (lambda (p)
                              (member 'read (file-or-directory-permissions p))))])
  f)

You can use path->string to produce the file names in string format instead. So, to create your list-all-files procedure:

(define (list-all-files path)
  (define (user-readable? f)
    (member 'read (file-or-directory-permissions f)))
  (for/list ([f (in-directory path user-readable?)])
    (path->string f)))

Then, you can filter the generated list using any predicate pred:

(filter pred (list-all-files "/some/path"))