vc 递归删除非空文件夹

时间:2022-11-22 00:39:03


我觉得这是一个非常不错的递归例子

头文件

#pragma once
#include <atlstr.h>
#include <io.h>
#include <string>
#include <iostream>
#include <windows.h>using namespace std;
BOOL Deleteall(CString path)
{
long handle = -1; //用于查找的句柄
CString strFilePath = "";
CString strLog = "";
strFilePath = strPath + "*.*"; struct _finddata_t fileinfo; //文件信息的结构体
handle=_findfirst(strFilePath,&fileinfo);
if (handle != -1)
{
do
{
int isSubDir = fileinfo.attrib & _A_SUBDIR;
if(isSubDir) //如果是文件夹
{
//CString FileName = fileinfo.name;
string strFileName(fileinfo.name );
if(strFileName.compare(".") != 0 && strFileName.compare("..") != 0)
{
CString NewPath = strPath + strFileName.c_str() + "\\" ;
DeleteAllFile(NewPath); //递归
}
}
else
{
CString str1(strPath);
string str2(fileinfo.name );
CString strfilepath = str1 + str2.c_str();
if(!DeleteFile(strfilepath))
{
strLog.Format("delete %s is failed,errorCode :%d\n", str2, GetLastError());
cout<<strLog;
}
}
}while(_findnext(handle, &fileinfo) != -1); // 遍历此目录下所有文件找配置文件??
_findclose(handle); if(!RemoveDirectory(strPath))
{
strLog.Format("delete %s is failed errorCode :%d\n", strPath, GetLastError());
cout<<strLog;
return FALSE;
}
else
{
strLog.Format("delete %s is succeed\n", strPath);
cout<<strLog;
}
}
return 0;}
main文件
void main()
{
CString path = "D:\\work\\" ;if(DeleteFiles(path))
cout<<"delete succeed"<<endl;
else
cout<<"delete fail"<<endl;
}