Delete Old Files (code snippet)

Description

This deletes files more than 1 hour old that match a filename pattern in a particular folder.

It is useful in managing temporary files to prevent an excessive number of files building up.

Requires: lfs and Delete File (code snippet) and Plain Text Substitution (code snippet)

Code

DeleteOldFiles.fh_lua
--[[
@Title:		Delete Old Files
@Author:	Mike Tate
@Version:	1.0
@LastUpdated:	March 2013
@Description:	Delete files accessed more than 1 hour ago
]]
function DeleteOldFiles(strFolder,strFile)
	local intTime = os.time() - 3600			-- Time in seconds one hour ago
	for strEntry in lfs.dir(strFolder) do			-- Search for files in the folder
		if strEntry ~= "." and strEntry ~= ".." then
			local strPath = strFolder..strEntry
			local tblAttr, strError = lfs.attributes(strPath)			-- Obtain file attributes
			if not tblAttr then tblAttr = { mode="attrfail", error=strError } end 
			if tblAttr.mode == "file" and strEntry:matches(strFile) then		-- Simple file with matching name?
				if tblAttr.access < intTime then DeleteFile(strPath) end	-- Delete if access time is an hour ago
			end
		end
	end
end -- function DeleteOldFiles

Usage

local strFolder = os.getenv("TEMP").."\\"		-- Temporary file folder
local strPrefix = os.tmpname():gsub("^\\","")		-- Unique filename prefix
local strPlugin = fhGetContextInfo("CI_PLUGIN_NAME")
local strFile_A = strPlugin..".css"			-- Temporary filename shared between Plugin runs
local strFile_B = strPrefix..strPlugin..".html"		-- Temporary filename unique to each Plugin run
DeleteOldFiles(strFolder,strPlugin)			-- Delete any old copies of the temporary files