#define _AFXDLL
#include <io.h>
#include <iostream>
#include <vector>
#include <string>
#include <afx.h>
using namespace std;
vector<string> getFolderList(const std::string &path)
{
std::vector<std::string> folderList;
//文件句柄
//long hFile = 0;
intptr_t hFile = 0;
//文件信息
_finddata_t fileinfo;
std::string allPath; //文件或文件的完整路径
if ((hFile = _findfirst(allPath.assign(path).append("/*").c_str(), &fileinfo)) != -1){
do{
if ((fileinfo.attrib & _A_SUBDIR)){
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0){ //目录
std::string folderPath = fileinfo.name;
folderList.push_back(folderPath);
}
else{//为文件
}
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
return folderList;
}
void DeleteDirectory(char *DirName, bool bNeedDel)
{
CFileFind tempFind;
char tempFileFind[MAX_PATH];
sprintf_s(tempFileFind, "%s\\*.*", DirName);
BOOL IsFinded = (BOOL)tempFind.FindFile(tempFileFind); //判断文件夹下是否存在文件
while (IsFinded) //存在
{
IsFinded = (BOOL)tempFind.FindNextFile(); //判断是否存在下一个文件
if (!tempFind.IsDots())
{
char foundFileName[MAX_PATH] = { 0 };
strcpy_s(foundFileName, tempFind.GetFileName().GetBuffer(MAX_PATH));
if (tempFind.IsDirectory())
{
char tempDir[MAX_PATH] = { 0 };
sprintf_s(tempDir, "%s\\%s", DirName, foundFileName);
DeleteDirectory(tempDir, bNeedDel);
}
else
{
char tempFileName[MAX_PATH] = { 0 };
sprintf_s(tempFileName, "%s\\%s", DirName, foundFileName);
DeleteFile(tempFileName);
}
}
}
tempFind.Close();
if (bNeedDel)
{
RemoveDirectory(DirName);
}
}
// 删除指定的文件夹
void DeleteDirectory(CString strDir)
{
if (strDir.IsEmpty())
{
RemoveDirectory(strDir);
return;
}
//首先删除文件及子文件夹
CFileFind ff;
BOOL bFound = ff.FindFile(strDir + _T("\\*"), 0);
while (bFound)
{
bFound = ff.FindNextFile();
if (ff.GetFileName() == _T(".") || ff.GetFileName() == _T("..")) continue;
//去掉文件(夹)只读等属性
SetFileAttributes(ff.GetFilePath(), FILE_ATTRIBUTE_NORMAL);
if (ff.IsDirectory())
{
//递归删除子文件夹
DeleteDirectory(ff.GetFilePath());
RemoveDirectory(ff.GetFilePath());
}
else
{
DeleteFile(ff.GetFilePath()); //删除文件
}
}
ff.Close();
//然后删除该文件夹
RemoveDirectory(strDir);
}
int main()
{
cout << "请输入要删除文件的文件夹路径....." << endl;
string filePath;
cin >> filePath;
cout << "请输入当前目录下要保留的子文件夹个数:" << endl;
int subfolderNum;
cin >> subfolderNum;
cout << "请输入当前目录文件夹更新时间:"<< endl;
int timeH;
cin >> timeH;
while (1)
{
vector<string> folderList;
folderList = getFolderList(filePath);
if (folderList.size() > subfolderNum)
{
for (int i = 0; i < folderList.size() - subfolderNum; i++)
{
string folderPath = filePath + "\\" + folderList[i];
DeleteDirectory(folderPath.c_str());
cout << "文件夹 :" << folderList[i] << " 删除完成" << endl;
}
}
Sleep(timeH * 3600000);
}
system("pause");
return 0;
}
版权声明:本文为weixin_41552975原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。