BOOL DeleteDirectory(LPCTSTR DirName)
{
CFileFind tempFind; //声明一个CFileFind类变量,以用来搜索
char tempFileFind[200]; //用于定义搜索格式
sprintf(tempFileFind,"%s//*.*",DirName);
//匹配格式为*.*,即该目录下的所有文件
BOOL IsFinded=(BOOL)tempFind.FindFile(tempFileFind);
//查找第一个文件
while(IsFinded)
{
IsFinded=(BOOL)tempFind.FindNextFile(); //递归搜索其他的文件
if(!tempFind.IsDots()) //如果不是"."目录
{
char foundFileName[200];
strcpy(foundFileName,tempFind.GetFileName().GetBuffer(200));
if(tempFind.IsDirectory()) //如果是目录,则递归地调用
{
//DeleteDirectory
char tempDir[200];
sprintf(tempDir,"%s//%s",DirName,foundFileName);
DeleteDirectory(tempDir);
}
else
{
//如果是文件则直接删除之
char tempFileName[200];
sprintf(tempFileName,"%s//%s",DirName,foundFileName);
DeleteFile(tempFileName);
}
}
}
tempFind.Close();
if(!RemoveDirectory(DirName)) //删除目录
{
AfxMessageBox("删除目录失败!",MB_OK);
return FALSE;
}
return TRUE;
}
方法二:(不使用MFC,在WTL/ATL中)
#ifdef INVALID_HANDLE_VALUE
#undef INVALID_HANDLE_VALUE
#define INVALID_HANDLE_VALUE ((HANDLE)((LONG_PTR)-1))
#endif
#define FILE_ATTRIBUTE_DIRECTORY 0x00000010
int DeleteDirectory(wchar_t* RemovePath)
{
if(RemovePath == NULL)
return 0;
if(wcslen(RemovePath) > (MAX_PATH - 5))
return 0;
wchar_t pcRoot[MAX_PATH+1]; //this dir
wchar_t pcTemp[MAX_PATH+1]; //this dir with "*.*" appended
_tcscpy(pcRoot,RemovePath);
int n;
n = wcslen(pcRoot);
if(pcRoot[n-1]!='//')
{
pcRoot[n] = '//';
n++;
pcRoot[n] = '/0';
}
_tcscpy(pcTemp,pcRoot);
wcscat(pcTemp,_T("*.*"));
WIN32_FIND_DATA f;
LPWIN32_FIND_DATA pf;
pf = (LPWIN32_FIND_DATA)&f;
HANDLE h;
h = FindFirstFile(pcTemp,pf);
if(h==INVALID_HANDLE_VALUE)
return 0;
BOOL b;
b = TRUE;
while(b)
{
if(wcscmp(f.cFileName,_T("."))==0 || wcscmp(f.cFileName,_T(".."))==0)
{
b = FindNextFile(h,pf);
continue;
}
wcscpy(pcTemp,pcRoot);
wcscat(pcTemp,f.cFileName);
if(f.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
{
DeleteDirectory(pcTemp);
_wrmdir(pcTemp);
}
else
DeleteFile(pcTemp);
b = FindNextFile(h,pf);
}
FindClose(h);
return 1;
}