Delete oldest file from a folder on Windows in C++/MFC



Following code deletes the oldest file from a folder. We need this when we wish to keep last X copies of a file for backup. So we would just delete the oldest one and create a new backup copy. Coded in C++/MFC.

 
//deletes by creation date
bool DeleteOldestFile(CString folderPath)
{
	if (!PathFileExists(folderPath)) return false;
 
	CFileFind finder;
	CString findString;
	CString filePath;
	WIN32_FILE_ATTRIBUTE_DATA fileAttributes;
	FILETIME oldestFileTime;
	CString oldestFilePath;
 
	ZeroMemory(&fileAttributes, sizeof(WIN32_FILE_ATTRIBUTE_DATA));
 
	//store current time in oldestFileTime so that we can compare in CompareFileTime to get older value
	SYSTEMTIME st;
	GetSystemTime(&st); // gets current time
	SystemTimeToFileTime(&st, &oldestFileTime);
 
 
	folderPath.TrimRight(_T('\\'));
	findString = folderPath + _T("\\*.*");
 
	BOOL bWorking = finder.FindFile(findString);
	while (bWorking)
	{
		bWorking = finder.FindNextFile();
 
		if (finder.IsDots())
			continue;
 
		if (finder.IsDirectory()) continue;
 
		filePath = finder.GetFilePath();
 
		::GetFileAttributesEx(filePath, GetFileExInfoStandard, &fileAttributes);
 
		if (CompareFileTime(&fileAttributes.ftCreationTime, &oldestFileTime) < 0) 
		{
			oldestFileTime = fileAttributes.ftCreationTime;
			oldestFilePath = filePath;
		}
 
	}
 
	finder.Close();
 
	if (oldestFilePath.IsEmpty()) return true;
 
	//delete the file finally
	return (DeleteFile(oldestFilePath) != 0);
 
}


Leave a Reply

Your email address will not be published. Required fields are marked *