Suppose I have variables dir
and file
containing strings representing a directory and a filename, respectively . What is the proper way in emacs lisp to join them into a full path to the file?
For example, if dir
is "/usr/bin"
and file
is "ls"
, then I want "/usr/bin/ls"
. But if instead dir
is "/usr/bin/"
, I still want the same thing, with no repeated slash.
Reading through the manual for Directory Names, you'll find the answer:
Given a directory name, you can combine it with a relative file name using
concat
:(concat dirname relfile)
Be sure to verify that the file name is relative before doing that. If you use an absolute file name, the results could be syntactically invalid or refer to the wrong file.
If you want to use a directory file name in making such a combination, you must first convert it to a directory name using
file-name-as-directory
:(concat (file-name-as-directory dirfile) relfile)
Don't try concatenating a slash by hand, as in
;;; Wrong! (concat dirfile "/" relfile)
because this is not portable. Always use
file-name-as-directory
.
Other commands that are useful are: file-name-directory
, file-name-nondirectory
, and others in the File Name Components section.