Delete Old Files

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 Code Snippets Delete File, File Exists, and Plain Text Substitution


@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 -- function DeleteOldFiles



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


Last update: 16 Dec 2020