【发布时间】:2011-10-05 21:48:39
【问题描述】:
我正在尝试从给定路径中包含的所有目录中删除基于模式的文件。我有以下内容,但它就像一个无限循环。当我取消循环时,不会删除任何文件。我哪里错了?
def recursive_delete (dirPath, pattern)
if (defined? dirPath and defined? pattern && File.exists?(dirPath))
stack = [dirPath]
while !stack.empty?
current = stack.delete_at(0)
Dir.foreach(current) do |file|
if File.directory?(file)
stack << current+file
else
File.delete(dirPath + file) if (pattern).match(file)
end
end
end
end
end
# to call:
recursive_delete("c:\Test_Directory\", /^*.cs$/)
【问题讨论】:
-
在目录递归中,通常要处理“.”。和“..”以一种特殊的方式。如果不这样做,就会经常发生无限循环。