【问题】怎样删除一个非空目录,及其目录里面所有内容: 【解答1】如果不进行递归删除。你可以使用API函数SHFileOperation,它可以一次删除目录及其下面的子目录和文件。 示例代码: BOOL DelTree(LPCTSTR lpszPath) { SHFILEOPSTRUCT FileOp; FileOp.fFlags = FOF_NOCONFIRMATION; FileOp.hNameMappings = NULL; FileOp.hwnd = NULL; FileOp.lpszProgressTitle = NULL; FileOp.pFrom = lpszPath; FileOp.pTo = NULL; FileOp.wFunc = FO_DELETE; return SHFileOperation(&FileOp;) == 0; }
【解答2】使用递归调用,逐个删除: 示例代码:
BOOL DeleteDirectory(char DirName)//如删除 DeleteDirectory(“c:\aaa”) { CFileFind tempFind; char tempFileFind[MAX_PATH]; sprintf(tempFileFind,”%s\.*”,DirName); BOOL IsFinded=(BOOL)tempFind.FindFile(tempFileFind); while(IsFinded) { IsFinded=(BOOL)tempFind.FindNextFile(); if(!tempFind.IsDots()) { char foundFileName[MAX_PATH]; strcpy(foundFileName,tempFind.GetFileName().GetBuffer(MAX_PATH)); if(tempFind.IsDirectory()) { char tempDir[MAX_PATH]; sprintf(tempDir,”%s\%s”,DirName,foundFileName); DeleteDirectory(tempDir); } else { char tempFileName[MAX_PATH]; sprintf(tempFileName,”%s\%s”,DirName,foundFileName); DeleteFile(tempFileName); } } } tempFind.Close(); if(!RemoveDirectory(DirName)) { MessageBox(0,”删除目录失败!”,”警告信息”,MB_OK);//比如没有找到文件夹,删除失败,可把此句删除 return FALSE; } return TRUE; }