码迷,mamicode.com
首页 > 其他好文 > 详细

newLISP 删除目录

时间:2014-09-06 16:10:33      阅读:348      评论:0      收藏:0      [点我收藏+]

标签:sp   on   c   new   ad   ef   app   file   as   

这是个很简单的需求,可是API只提供了一个几乎没什么用的函数

remove-dir 要求目录必须为空, 99%的情况是目录不为空。

因此我写了一个函数来递归删除目录树:

(define (make-sure-folder-path-end-of-slash dir-path)
  (if (!= (last dir-path) "/")
      (push "/" dir-path -1)
    )
  dir-path
)

(define (no-sub-files dir-path)
  (not (directory dir-path {[^(\.$)]})))

(define (delete-dir dir-path)
  ;; check dir-path
  (unless (directory? dir-path)
    (throw-error (string dir-path " folder does not exist")))

  ;; append slash to dir-path
  (set ‘dir-path (make-sure-folder-path-end-of-slash dir-path))

  ;; process sub files
  (let (sub-files (directory dir-path {[^(\.$)]}))
    (if sub-files
	(begin
	 ;; iterate all sub files
	 (dolist (nde sub-files)
	   (if (directory? (append dir-path nde))
	       (delete-dir (append dir-path nde) file-op ext-context)
	     (let (file-path (append dir-path nde))
	       (println (string "delete file " file-path ": " (file-info file-path)))
	       (delete-file file-path ext-context))))
	 (if (no-sub-files dir-path)
	     (begin
	      (println (string "delete folder " dir-path ": " (file-info dir-path)))
	      (remove-dir dir-path))
	     )
	 )
      (begin
       (println "no sub files in " dir-path " folder, delete this folder")
       (remove-dir dir-path))
      )
    )
)

测试方法:

dean@dean-Latitude-3330:~/Downloads$ mkdir -p x/x2/x3; touch x/x2/x3/z;touch x/x2/m;touch x/.sss; touch x/a.x;
dean@dean-Latitude-3330:~/Downloads$ tree x -a
x
├── a.x
├── .sss
└── x2
    ├── m
    └── x3
        └── z

2 directories, 4 files

然后执行newlisp函数:

> (delete-dir "/home/dean/Downloads/x")
delete file /home/dean/Downloads/x/a.x: (0 33204 0 1000 1000 1409987071 1409987071 1409987071)
delete file /home/dean/Downloads/x/x2/x3/z: (0 33204 0 1000 1000 1409987071 1409987071 1409987071)
delete folder /home/dean/Downloads/x/x2/x3/: (4096 16893 0 1000 1000 1409987075 1409987075 1409987075)
delete file /home/dean/Downloads/x/x2/m: (0 33204 0 1000 1000 1409987071 1409987071 1409987071)
delete folder /home/dean/Downloads/x/x2/: (4096 16893 0 1000 1000 1409987075 1409987075 1409987075)
delete file /home/dean/Downloads/x/.sss: (0 33204 0 1000 1000 1409987071 1409987071 1409987071)
delete folder /home/dean/Downloads/x/: (4096 16893 0 1000 1000 1409987075 1409987075 1409987075)
true


newLISP 删除目录

标签:sp   on   c   new   ad   ef   app   file   as   

原文地址:http://blog.csdn.net/csfreebird/article/details/39100981

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!