2013-05-06 53 views
0

我需要定义一个函数,它将在没有不必要的副作用(即打开的缓冲区)的情况下确保文件已准备好可供读取。确保文件路径存在以供读取

这是我到目前为止有:

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

这(似乎)时,该目录存在做工精细。不幸的是,我不能确定是这种情况(因为变量可能会发生变化等)。有没有什么办法可以将make-directory纳入所有这些,或者更好的解决方法是什么?

我理想的使用情况是这样的:

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

这就需要有这样的签名:

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

,但我真的不知道该怎么做。 :/


这是所有a Stack Exchange mode为Emacs新链接:sx.el,通过:-)

+0

我不确定我是否理解签名'(file&rest body)'部分;我建议你就此提出一个单独的问题。 – sds 2013-05-07 13:22:54

+0

@sds嗯......为什么? 'body'将是'file'后的所有内容。因此''(确保存在“foo.txt”(消息“文件存在”)(消息“不,实际上,它确实相信我”))'会设置'file =>“foo.txt”和' body =>'((message“...”)(message“...”))'然后可以用'mapc'和'eval'评估。 – 2013-06-01 14:31:38

+0

'&body'用于宏而不是函数。 – sds 2013-06-02 01:33:34

回答

3

至于建议由@Stefan的方式,

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

这应该工作在包括windows和unix。

编辑:实际上,你可以通过追加t参数write-region废除该文件存在检查,但如果它已经存在(就像touch),这将改变文件的修改时间。

只是为了比较,Common Lisp的版本是这样的:

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

(见openensure-file-exists)。

+0

尽管UNIX系统上的所有内容都非常棒,但在Windows上无法使用。谢谢:) – 2013-05-06 12:25:50

+1

为什么使用'touch'时,你可以使用'(写区域“”无无'沉默)'。 – Stefan 2013-05-06 13:05:33

+0

@Stefan:谢谢你的建议;现在它是便携式! – sds 2013-05-06 13:22:15