file - Ensure filepath exists for reading -


i need define function will, without unnecessary side effects (i.e. open buffer), ensure file exists ready reading.

here have far:

(defun ensure-existence (file)   (if (not (file-exists-p file))     (kill-buffer      (save-buffer       (find-file-noselect file)))) 

which (seems to) work fine when directory exists. unfortunately, can't sure case (since variables may change, etc.). there way incorporate make-directory of or, better yet, there cleaner solution?

my ideal use case this:

(ensure-existence "new/path/to/new/file.txt"    (func1 arg1)    (func2 arg2a arg2b)    (...)) 

which necessitate signature this:

(defun ensure-existence (file &rest body) ...) 

but don't know how that. :/


this a stack exchange mode emacs new link: sx.el, way :-)

as suggested @stefan,

(defun ensure-file-exists (file)   (unless (file-exist-p file)     (make-directory (file-name-directory file) t)     (write-region "" nil file nil 'silent))) 

this should work on both windows , unix.

edit: actually, can away file existence check passing append t argument write-region, change modification time of file if exists (just touch).

just comparison, common lisp version this:

(defun ensure-file-exists (file &key verbose)   (ensure-directories-exist foo :verbose verbose)   (open file :direction :probe :if-does-not-exist :create)) 

(see open , ensure-file-exists).


Comments