C++ method to delete log files in the specified folder N days and before
- 2020-05-05 11:33:05
- OfStack
This example shows how to delete the log files of C++ for N days and before the specified folder. Share with you for your reference. The details are as follows:
// Function: delete nDays Day and previous log files
// @nDays: 0- Do not delete the log, 3- delete 3 Day and previous log ( Keep a log of today, yesterday and the day before yesterday ) ...
void CRecordLog::ClearLog(UINT nDays) // delete N Days ago log
{
if (nDays > 0)
{
WIN32_FIND_DATA FindFileData;
CString sAllFile = m_sLogFolder + "\\*.log";
HANDLE hFind = ::FindFirstFile(sAllFile, &FindFileData);
if(INVALID_HANDLE_VALUE == hFind) return;
while(TRUE)
{
if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) // Encountered folder
{
}
else // In the file
{
CString sFileName;
sFileName.Format("%s", FindFileData.cFileName);
if (sFileName.GetLength() == 14)
{
CString sFileFullPath = m_sLogFolder + "\\" + sFileName;// File full path
sFileName.Replace("-", "");
__int64 nFileName = _atoi64(sFileName); // Date of acquisition, such as: 20101030
CTime tNowTime = CTime::GetCurrentTime();
tNowTime = tNowTime - CTimeSpan(nDays, 0, 0, 0); // Point to the nDays The day before
__int64 nNowTime = _atoi64(tNowTime.Format("%Y%m%d"));
if (20000000 < nFileName && nFileName < nNowTime)
{
::DeleteFile(sFileFullPath);
}
}
}
if(!FindNextFile(hFind, &FindFileData))
break;
}
FindClose(hFind);
}
}
Supplement: the file name format of the deleted log file above is: 2011-02-08.log
I hope this article is helpful for your C++ programming.