首页 > 代码库 > newLISP 删除目录
newLISP 删除目录
这是个很简单的需求,可是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 删除目录
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。