Given the path of a directory, how can I return the path of the newest file in that directory?
Using built-in APIs can achieve as well:
(defun latest-file (path)
  "Get latest file (including directory) in PATH."
  (car (directory-files path 'full nil #'file-newer-than-file-p)))
(latest-file "~/.emacs.d") ;; => "/Users/xcy/.emacs.d/var"
If you also needs files under sub-directory, use directory-files-recursively rather than directory-files. If you want to exclude directories, filter the file/directory list first by using file-directory-p.
Using f:
(defun aj-fetch-latest (path)
  (let ((e (f-entries path)))
    (car (sort e (lambda (a b)
                   (not (time-less-p (aj-mtime a)
                                     (aj-mtime b))))))))
(defun aj-mtime (f) (let ((attrs (file-attributes f))) (nth 5 attrs)))
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With