YYW'S BLOG

知识的分享就是知识的获得
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

【Ruby】删除旧文件

Posted on 2011-06-20 17:03  阿武  阅读(427)  评论(0编辑  收藏  举报

一个删除旧文件的函数,通常用于删除较老的log文件。

 

 module FileUtils2
    ONE_DAY_SECONDS 
= 60*60*24
    
# remove the old files, return the number of files that removed.    
    def remove_old_files(dir_path, days_ago)
        count 
= 0    
        dir_path2 
= dir_path + File::ALT_SEPARATOR unless dir_path.end_with?(File::ALT_SEPARATOR)
        d 
= Dir.new dir_path2    

        now 
= Time.now
        
        d
.each  {|filename|     
            
next if filename == '.' or filename == '..'

            file_path 
= dir_path2 + filename
            
next if File.directory?(file_path)
            
            f 
= File.new(file_path)
            diff 
= now.to_i - f.mtime.to_i
            f
.close
            day 
= diff/ONE_DAY_SECONDS
            
            
next if day <= days_ago
            
            File
.delete(file_path)
            puts 
"Delete: #{file_path}." 
            count 
+= 1
        }
        
return count
    end
end