一万のファイルがあるディレクトリから条件に合うファイルを一つ取り出す - lisp-cookbook-ja/common-lisp GitHub Wiki

一万のファイルがあるディレクトリから条件に合うファイルを一つ取り出す例です

directory でディレクトリの内容を取得し条件に合う最初のものを返す

;;; ファイルの拡張子が .txt かを判定
(defun txt-p (path)
  (string= "TXT" (pathname-type path :case :common)))

;;; /tmp/10000 or C:\tmp\10000 etc...
(defparameter *dir*
  (make-pathname :directory '(:absolute "TMP" "10000") :case :common))


(dolist (f (directory
            (merge-pathnames *dir*
                             (make-pathname :name :wild
                                            :type "TXT"
                                            :case :common))))
  (when (txt-p f)
    (return f)))
;⇒ #P"/tmp/10000/00001.txt"
#|------------------------------------------------------------|
Evaluation took:
  1.124 seconds of real time
  1.116070 seconds of total run time (0.908057 user, 0.208013 system)
  99.29% CPU
  2,688,891,030 processor cycles
  46,603,728 bytes consed

Intel(R) Core(TM)2 Duo CPU     P8600  @ 2.40GHz
 |------------------------------------------------------------|#

処理系依存の機能でイテレータを使った場合

#+sbcl
(sb-impl::with-native-directory-iterator (p (namestring *dir*))
  (loop :for p := (p) :while p
        :when (txt-p p) :return p))
;⇒ "05524.txt"
#|------------------------------------------------------------|
Evaluation took:
  0.002 seconds of real time
  0.000000 seconds of total run time (0.000000 user, 0.000000 system)
  0.00% CPU
  4,192,794 processor cycles
  0 bytes consed

Intel(R) Core(TM)2 Duo CPU     P8600  @ 2.40GHz
 |------------------------------------------------------------|#