返回父目录绝对路径的函数


10
    (parent-dir "/home/sk/parent/ab.el")

    "/home/sk/parent"

然后,

(parent-dir "/home/sk/parent")

"/home/sk"

任何elisp函数parent-dir都可以为文件路径和目录路径提供基本路径吗?

Answers:


14

file-name-directory 完成您的要求。

但是,(file-name-directory "/home/sk/parent/")(带有斜杠)返回相同的目录,而不是其父目录。

这就是我想您真正想要的:

(file-name-directory (directory-file-name "/home/sk/parent/ab.el")) ; => "/home/sk/parent/"
(file-name-directory (directory-file-name "/home/sk/parent/")) ; => "/home/sk/"
(file-name-directory (directory-file-name "/home/sk/parent")) ; => "/home/sk/"

Dired +使用此功能:

(defun diredp-parent-dir (file &optional relativep)
  "Return the parent directory of FILE, or nil if none.
Optional arg RELATIVEP non-nil means return a relative name, that is,
just the parent component."
  (let ((parent  (file-name-directory (directory-file-name (expand-file-name file))))
        relparent)
    (when relativep
      (setq relparent  (file-name-nondirectory (directory-file-name parent))))
    (and (not (equal parent file))  (or relparent  parent))))

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.